Пример #1
0
        private EntityCollection <TeamEntity> GetTeamsWithSameVenueAndMatchTime(TeamEntity team, RoundEntity round)
        {
            var resultTeams = new EntityCollection <TeamEntity>();

            TimeSpan?teamStartTime = team.MatchTime;
            TimeSpan?teamEndTime   = teamStartTime?.Add(_matchPlanner.PlannedDurationOfMatch);

            // first get a list of other teams with same venue and match day of the week
            List <int> tmpTeams = round.TeamCollectionViaTeamInRound.FindMatches(TeamFields.VenueId == team.VenueId & TeamFields.MatchDayOfWeek == (int)team.MatchDayOfWeek & TeamFields.Id != team.Id);

            foreach (var index in tmpTeams)
            {
                TimeSpan?otherStartTime = round.TeamCollectionViaTeamInRound[index].MatchTime;
                TimeSpan?otherEndTime   = otherStartTime?.Add(_matchPlanner.PlannedDurationOfMatch);

                if ((otherStartTime <= teamStartTime && otherEndTime >= teamStartTime) || (otherStartTime <= teamEndTime && otherEndTime >= teamEndTime))
                {
                    resultTeams.Add(round.TeamCollectionViaTeamInRound[index]);
                }
            }

            // list is expected to contain at least one team
            resultTeams.Add(team);

            return(resultTeams);
        }
Пример #2
0
        public void UpdateETAs()
        {
            DateTime now     = DateTime.Now;
            TimeSpan?lastETD = null;

            for (int i = 0; i < Stops.Count; i++)
            {
                var stop = Stops[i];

                switch (stop.Status)
                {
                case RoutеStopStatus.Pending:
                    if (lastETD != null && stop.LegDuration != null)
                    {
                        stop.ETA = lastETD?.Add((TimeSpan)stop.LegDuration);
                        lastETD  = stop.ETA?.Add(stop.StopDuration);
                    }
                    else
                    {
                        stop.ETA = lastETD = null;
                    }
                    break;

                case RoutеStopStatus.Enroute:
                    stop.ETA = stop.LegDuration;
                    lastETD  = stop.ETA?.Add(stop.StopDuration);
                    break;

                case RoutеStopStatus.Arrived:
                    stop.ETA = null;
                    var etd = stop.ArrivalTime?.Add(stop.StopDuration);
                    if (stop.Kind != RouteStopKind.StartPoint && etd != null && etd > now)
                    {
                        lastETD = ((DateTime)etd).Subtract(now);
                    }
                    else
                    {
                        lastETD = TimeSpan.Zero;
                    }
                    break;

                case RoutеStopStatus.Departed:
                    stop.ETA = null;
                    lastETD  = TimeSpan.Zero;
                    break;
                }

                stop.UpdateInfo();
            }
        }
Пример #3
0
        public bool Set <T>(string key, Func <T> func, TimeSpan?expiresIn, When when, CommandFlags commandFlags)
        {
            var realKey = Wrapper.GetRealKey(key);

            using (var locker = new RedLockClient(HashHelper.GetHashedString(HashType.MD5, realKey), DependencyResolver.Current.ResolveService <ILogger <RedLockClient> >()))
            {
                if (locker.TryLock())
                {
                    return(Wrapper.Database.StringSet(realKey, Wrapper.Wrap(func()), expiresIn?.Add(GetRandomCacheExpiry()), when,
                                                      commandFlags));
                }
                Logger.LogInformation($"get lock failed,update cache fail,cache key:{realKey},current time:{DateTime.Now:yyyy-MM-dd HH:mm:ss.ffffff}");
                return(false);
            }
        }
Пример #4
0
        /// <summary>
        /// Check for possibility of next attempt.
        /// </summary>
        /// <remarks>
        /// Increments the attempts counter, if attempt is allowed.
        /// Calculates time to wait corresponding to BackoffPolicy before next try.
        /// </remarks>
        /// <param name="elapsedTime">Time eplased since first attempt</param>
        /// <param name="attempts">Attempts counter</param>
        /// <param name="timeToWait">Calculated time to wait before next attempt</param>
        /// <returns>True if the try limit is not reached yet, false otherwise.</returns>
        protected bool TryAgain(TimeSpan?elapsedTime, ref int attempts, out TimeSpan timeToWait)
        {
            timeToWait = TimeSpan.Zero;

            if (attempts >= RetryPolicy.RetryLimit)
            {
                return(false);
            }

            TimeSpan nextTimeToWait = RetryPolicy.BackoffPolicy != null?RetryPolicy.BackoffPolicy.CalculateBackoff(attempts + 1, RetryPolicy.Factor) : TimeSpan.Zero;

            if (elapsedTime?.Add(nextTimeToWait) >= RetryPolicy.TimeLimit)
            {
                return(false);
            }

            timeToWait = nextTimeToWait;
            ++attempts;
            return(true);
        }
Пример #5
0
        public List <Agendamento> Completo(int meses, int idOdontologista, int idClinica)
        {
            var conexao = new Connection(new System.Data.SqlClient.SqlConnection());

            using (var repositorio = new AgendaRepositorio(conexao))
            {
                var agenda = repositorio.Buscar(new Agenda()
                {
                    IdClinica = idClinica, IdOdontologista = idOdontologista
                }).FirstOrDefault();
                if (agenda == null)
                {
                    return(null);
                }
                using (var repositorioAgendamento = new AgendamentoRepositorio(conexao))
                {
                    var agendamentos = repositorioAgendamento.Buscar(new Agendamento()
                    {
                        IdAgenda = agenda.Id
                    });

                    using (var repositorioSemana = new SemanaAgendaRepositorio(conexao))
                    {
                        var semana = repositorioSemana.Buscar(new SemanaAgenda()
                        {
                            IdClinica = idClinica, IdOdontologista = idOdontologista
                        });

                        using (var repositorioDia = new DiaAgendaRepositorio(conexao))
                        {
                            var dia = repositorioDia.Buscar(new DiaAgenda()
                            {
                                IdClinica = idClinica, IdOdontologista = idOdontologista
                            });

                            using (var repositorioDayOff = new AgendaDayOffRepositorio(conexao))
                            {
                                var dayOff = repositorioDayOff.Buscar(new AgendaDayOff()
                                {
                                    IdClinica = idClinica, IdOdontologista = idOdontologista
                                });

                                var listaAgendamentos = new List <Agendamento>();
                                var dataAtual         = DateTime.Now;

                                while (dataAtual <= DateTime.Now.AddMonths(meses))
                                {
                                    if (dayOff.Where(x => x.Data.Date == dataAtual.Date).Count() >= 1)
                                    {
                                        dataAtual.AddDays(1);
                                        continue;
                                    }

                                    if (dia.Where(x => x.Data.Date == dataAtual.Date).Count() >= 1)
                                    {
                                        foreach (var d in dia.Where(x => x.Data.Date == dataAtual.Date))
                                        {
                                            TimeSpan horario = d.HorarioAtendimentoInicio;
                                            do
                                            {
                                                if (agendamentos.Where(x => x.Data.Date == dataAtual.Date &&
                                                                       x.Horario >= horario &&
                                                                       x.Horario < horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0))
                                                                       ).Count() > 0)
                                                {
                                                    var agendamento = agendamentos.Where(x => x.Data.Date == dataAtual.Date &&
                                                                                         x.Horario >= horario &&
                                                                                         x.Horario < horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0))
                                                                                         ).FirstOrDefault();

                                                    listaAgendamentos.Add(new Agendamento()
                                                    {
                                                        Id         = agendamento.Id,
                                                        Data       = agendamento.Data,
                                                        Horario    = agendamento.Horario,
                                                        IdAgenda   = agenda.Id,
                                                        IdOdonto   = agenda.IdOdontologista,
                                                        IdPaciente = agendamento.IdPaciente
                                                    });
                                                }
                                                else
                                                {
                                                    listaAgendamentos.Add(new Agendamento()
                                                    {
                                                        Id         = 0,
                                                        Data       = dataAtual.Date,
                                                        Horario    = horario,
                                                        IdAgenda   = agenda.Id,
                                                        IdOdonto   = agenda.IdOdontologista,
                                                        IdPaciente = 0
                                                    });
                                                }
                                                horario = horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0));
                                            } while (horario <= d.HorarioAtendimentoTermino);
                                        }
                                    }

                                    if (semana.Where(x => x.DiaSemana == (int)dataAtual.DayOfWeek + 1).Count() >= 1)
                                    {
                                        foreach (var s in semana.Where(x => x.DiaSemana == (int)dataAtual.DayOfWeek + 1))
                                        {
                                            TimeSpan horario = s.HorarioAtendimentoInicio;
                                            do
                                            {
                                                if (agendamentos.Where(x => x.Data.Date == dataAtual.Date &&
                                                                       x.Horario >= horario &&
                                                                       x.Horario < horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0))
                                                                       ).Count() > 0)
                                                {
                                                    var agendamento = agendamentos.Where(x => x.Data.Date == dataAtual.Date &&
                                                                                         x.Horario >= horario &&
                                                                                         x.Horario < horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0))
                                                                                         ).FirstOrDefault();

                                                    listaAgendamentos.Add(new Agendamento()
                                                    {
                                                        Id         = agendamento.Id,
                                                        Data       = agendamento.Data,
                                                        Horario    = agendamento.Horario,
                                                        IdAgenda   = agenda.Id,
                                                        IdOdonto   = agenda.IdOdontologista,
                                                        IdPaciente = agendamento.IdPaciente
                                                    });
                                                }
                                                else
                                                {
                                                    listaAgendamentos.Add(new Agendamento()
                                                    {
                                                        Id         = 0,
                                                        Data       = dataAtual.Date,
                                                        Horario    = horario,
                                                        IdAgenda   = agenda.Id,
                                                        IdOdonto   = agenda.IdOdontologista,
                                                        IdPaciente = 0
                                                    });
                                                }
                                                horario = horario.Add(new TimeSpan(0, 0, agenda.TempoAtendimento, 0, 0));
                                            } while (horario <= s.HorarioAtendimentoTermino);
                                        }
                                    }
                                    dataAtual = dataAtual.AddDays(1);
                                }
                                return(listaAgendamentos);
                            }
                        }
                    }
                }
            }
        }
Пример #6
0
        public int UpdateImages(ManagedSecurityContext sec)
        {
            GetACL().Check(sec, DataOperation.Update);

            int result   = 0;
            Uri basehref = null;

            Uri.TryCreate(mInstance.LinkUrl, UriKind.Absolute, out basehref);

            IList items = Session.CreateCriteria(typeof(AccountFeedItem))
                          .Add(Expression.Eq("AccountFeed.Id", mInstance.Id))
                          .List();

            foreach (AccountFeedItem item in items)
            {
                IList <HtmlImage> images = null;

                try
                {
                    images = HtmlImageExtractor.Extract(item.Description, basehref);
                }
                catch
                {
                    continue;
                }

                TimeSpan tsDistribution = new TimeSpan(0, 30, 0);

                foreach (HtmlImage image in images)
                {
                    AccountFeedItemImg x_img = null;

                    // images may appear only once, repeating images don't get updated
                    // nor images linked from multiple feeds or feed items

                    x_img = (AccountFeedItemImg)Session.CreateCriteria(typeof(AccountFeedItemImg))
                            .Add(Expression.Eq("Url", image.Src)).UniqueResult();

                    if (x_img != null)
                    {
                        // image already exists
                        continue;
                    }

                    x_img                 = new AccountFeedItemImg();
                    x_img.Created         = item.Created.Subtract(tsDistribution); // shuffle images
                    tsDistribution        = tsDistribution.Add(new TimeSpan(0, 30, 0));
                    x_img.Modified        = DateTime.UtcNow;
                    x_img.AccountFeedItem = item;
                    x_img.Description     = image.Alt;
                    x_img.Interesting     = false;
                    x_img.Url             = image.Src;

                    // fetch the image to get its size
                    try
                    {
                        WebClient client = new WebClient();
                        client.Headers["Accept"]     = "*/*";
                        client.Headers["User-Agent"] = ManagedConfiguration.GetValue(Session, "SnCore.Web.UserAgent", "SnCore/1.0");
                        byte[] data = client.DownloadData(x_img.Url);
                        if (data == null)
                        {
                            throw new Exception("Missing file data.");
                        }
                        ThumbnailBitmap bitmap = new ThumbnailBitmap(data);
                        x_img.Thumbnail = bitmap.Thumbnail;
                        x_img.Visible   = mInstance.PublishImgs;

                        // hide images smaller than the thumbnail size
                        if (bitmap.FullSize.Height < ThumbnailBitmap.s_ThumbnailSize.Height ||
                            bitmap.FullSize.Width < ThumbnailBitmap.s_ThumbnailSize.Width)
                        {
                            x_img.Visible = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        x_img.LastError = ex.Message;
                        x_img.Visible   = false;
                    }

                    Session.Save(x_img);
                    result++;
                }
            }

            return(result);
        }
Пример #7
0
        private void _updateTimer_Elapsed(object sender)
        {
            var scsTelemetry = SharedMemory.Update <SCSTelemetry>();

            // check if sdk is NOT running
            if (!scsTelemetry.SdkActive && !paused)
            {
                // if so don't check so often the data
                var tsInterval = new TimeSpan(0, 0, 0, 0, DefaultPausedUpdateInterval);
                _updateTimer.Change(tsInterval.Add(tsInterval), tsInterval);
                paused = true;
                // if sdk not active we don't need to do something
                return;
            }

            if (paused && scsTelemetry.SdkActive)
            {
                // ok sdk is active now
                paused = false;
                resume(); // going back to normal update rate
            }

            var time    = scsTelemetry.Timestamp;
            var updated = false;

            if (time != lastTime || wasPaused != scsTelemetry.Paused)
            {
                // time changed or game state change -> update data
                Data?.Invoke(scsTelemetry, true);
                wasPaused = scsTelemetry.Paused;
                lastTime  = time;
                updated   = true;
            }

            //TODO: make it nicer thats a lot of code for such less work
            // Job start event
            if (wasOnJob != scsTelemetry.SpecialEventsValues.OnJob)
            {
                wasOnJob = scsTelemetry.SpecialEventsValues.OnJob;
                if (wasOnJob)
                {
                    if (!updated)
                    {
                        Data?.Invoke(scsTelemetry, true);
                        updated = true;
                    }

                    JobStarted?.Invoke(this, new EventArgs());
                }
            }

            if (cancelled != scsTelemetry.SpecialEventsValues.JobCancelled)
            {
                cancelled = scsTelemetry.SpecialEventsValues.JobCancelled;
                if (cancelled)
                {
                    if (!updated)
                    {
                        Data?.Invoke(scsTelemetry, true);
                        updated = true;
                    }

                    JobCancelled?.Invoke(this, new EventArgs());
                }
            }

            if (delivered != scsTelemetry.SpecialEventsValues.JobDelivered)
            {
                delivered = scsTelemetry.SpecialEventsValues.JobDelivered;
                if (delivered)
                {
                    if (!updated)
                    {
                        Data?.Invoke(scsTelemetry, true);
                        updated = true;
                    }

                    JobDelivered?.Invoke(this, new EventArgs());
                }
            }

            if (fined != scsTelemetry.SpecialEventsValues.Fined)
            {
                fined = scsTelemetry.SpecialEventsValues.Fined;
                if (fined)
                {
                    Fined?.Invoke(this, new EventArgs());
                }
            }

            if (tollgate != scsTelemetry.SpecialEventsValues.Tollgate)
            {
                tollgate = scsTelemetry.SpecialEventsValues.Tollgate;
                if (tollgate)
                {
                    Tollgate?.Invoke(this, new EventArgs());
                }
            }

            if (ferry != scsTelemetry.SpecialEventsValues.Ferry)
            {
                ferry = scsTelemetry.SpecialEventsValues.Ferry;
                if (ferry)
                {
                    if (!updated)
                    {
                        Data?.Invoke(scsTelemetry, true);
                        updated = true;
                    }

                    Ferry?.Invoke(this, new EventArgs());
                }
            }

            if (train != scsTelemetry.SpecialEventsValues.Train)
            {
                train = scsTelemetry.SpecialEventsValues.Train;
                if (train)
                {
                    if (!updated)
                    {
                        Data?.Invoke(scsTelemetry, true);
                        updated = true;
                    }

                    Train?.Invoke(this, new EventArgs());
                }
            }

            if (refuel != scsTelemetry.SpecialEventsValues.Refuel)
            {
                refuel = scsTelemetry.SpecialEventsValues.Refuel;
                if (scsTelemetry.SpecialEventsValues.Refuel)
                {
                    RefuelStart?.Invoke(this, new EventArgs());
                }
                else
                {
                    RefuelEnd?.Invoke(this, new EventArgs());
                }
            }

            if (refuelPayed != scsTelemetry.SpecialEventsValues.RefuelPayed)
            {
                refuelPayed = scsTelemetry.SpecialEventsValues.RefuelPayed;
                if (scsTelemetry.SpecialEventsValues.RefuelPayed)
                {
                    RefuelPayed?.Invoke(this, new EventArgs());
                }
            }

            // currently the design is that the event is called, doesn't matter if data changed
            // also the old demo didn't used the flag and expected to be refreshed each call
            // so without making a big change also call the event without update with false flag
            if (!updated)
            {
                Data?.Invoke(scsTelemetry, false);
            }
        }
Пример #8
0
 public HourGroup(TimeSpan time)
 {
     Events         = new ObservableCollection <EventAdapter>();
     TimeAsTimeSpan = time;
     Time           = $"{time:hh\\:mm} : {time.Add(TimeSpan.FromHours(1)):hh\\:mm}";
 }
Пример #9
0
        ///<summary>Gets open time slots based on the parameters passed in.
        ///Open time slots are found by looping through the passed in operatories and finding openings that can hold the entire appointment.
        ///Make sure that timePattern is always passed in utilizing 5 minute increments (no conversion will be applied to the pattern passed in).
        ///Providers passed in will be the only providers considered when looking for available time slots.
        ///Passing in a null clinic will only consider operatories with clinics set to 0 (unassigned).
        ///The timeslots on and between the Start and End dates passed in will be considered and potentially returned as available.
        ///Optionally set defNumApptType if looking for time slots for New Pat Appt which will apply the DefNum to all time slots found.
        ///Throws exceptions.</summary>
        public static List <TimeSlot> GetTimeSlotsForRange(DateTime dateStart, DateTime dateEnd, string timePattern, List <long> listProvNums
                                                           , List <Operatory> listOperatories, List <Schedule> listSchedules, Clinic clinic, long defNumApptType = 0, Logger.IWriteLine log = null, bool isDoubleBookingAllowed = true)
        {
            //No need to check RemotingRole; no call to db.
            //Order the operatories passed in by their ItemOrder just in case they were passed in all jumbled up.
            List <long> listOpNums = listOperatories.OrderBy(x => x.ItemOrder).Select(x => x.OperatoryNum).Distinct().ToList();

            //Remove all schedules that fall outside of the date range passed in.  Only consider the date right now, the time portion is handled later.
            listSchedules.RemoveAll(x => !x.SchedDate.Date.Between(dateStart.Date, dateEnd.Date));
            List <Schedule> listProviderSchedules = listSchedules.FindAll(x => x.BlockoutType == 0);
            List <Schedule> listBlockoutSchedules = listSchedules.FindAll(x => x.BlockoutType > 0);
            //Get every single appointment for all operatories within our start and end dates for double booking and overlapping consideration.
            List <Appointment> listApptsForOps = Appointments.GetAppointmentsForOpsByPeriod(Operatories.GetDeepCopy(true)
                                                                                            .Where(x => (clinic == null) || (x.ClinicNum == clinic.ClinicNum)).Select(x => x.OperatoryNum).ToList(), dateStart, dateEnd, log);

            log?.WriteLine("listProviderSchedules:\r\n\t" + string.Join(",\r\n\t",
                                                                        listProviderSchedules.Select(x => x.ScheduleNum + " - " + x.SchedDate.ToShortDateString() + " " + x.StartTime)), LogLevel.Verbose);
            log?.WriteLine("listBlockoutSchedules:\r\n\t" + string.Join(",\r\n\t",
                                                                        listBlockoutSchedules.Select(x => x.ScheduleNum + " - " + x.SchedDate.ToShortDateString() + " " + x.StartTime)), LogLevel.Verbose);
            log?.WriteLine("listApptsForOps:\r\n\t"
                           + string.Join(",\r\n\t", listApptsForOps.Select(x => x.AptNum + " - " + x.AptDateTime + " OpNum: " + x.Op)), LogLevel.Verbose);
            //We need to be conscious of double booking possibilities.  Go get provider schedule information for the date range passed in.
            Dictionary <DateTime, List <ApptSearchProviderSchedule> > dictProvSchedules = Appointments.GetApptSearchProviderScheduleForProvidersAndDate(
                listProvNums, dateStart, dateEnd, listProviderSchedules, listApptsForOps);
            //Split up the operatory specific provider schedules from the dynamic ones because each will have different operatory logic.
            List <Schedule>   listProviderSchedulesWithOp = listProviderSchedules.FindAll(x => x.Ops.Intersect(listOpNums).ToList().Count > 0);
            List <ScheduleOp> listScheduleOps             = ScheduleOps.GetForSchedList(listProviderSchedules);
            //Now we need to get the dynamic schedules (not assigned to a specific operatory).
            List <Schedule> listProviderDynamicSchedules = listProviderSchedules.FindAll(x => !listScheduleOps.Exists(y => y.ScheduleNum == x.ScheduleNum));
            //Now that we have found all possible valid schedules, find all the unique time slots from them.
            List <Schedule> listProviderSchedulesAll = new List <Schedule>(listProviderSchedulesWithOp);

            listProviderSchedulesAll.AddRange(listProviderDynamicSchedules);
            listProviderSchedulesAll = listProviderSchedulesAll.OrderBy(x => x.SchedDate).ToList();
            List <TimeSlot> listAvailableTimeSlots = new List <TimeSlot>();
            List <DateTime> listUniqueDays         = new List <DateTime>();
            int             timeIncrement          = PrefC.GetInt(PrefName.AppointmentTimeIncrement);

            //Loop through all schedules five minutes at a time to find time slots large enough that have no appointments and no blockouts within them.
            foreach (Schedule schedule in listProviderSchedulesAll)
            {
                DateTime dateSched = schedule.SchedDate;
                //Straight up ignore schedules in the past.  This should not be possible but this is just in case.
                if (dateSched.Date < DateTime.Today)
                {
                    continue;
                }
                if (!listUniqueDays.Contains(dateSched))
                {
                    listUniqueDays.Add(dateSched);
                }
                TimeSpan timeSchedStart = schedule.StartTime;
                TimeSpan timeSchedStop  = schedule.StopTime;
                //Now, make sure that the start time is set to a starting time that makes sense with the appointment time increment preference.
                int minsOver = (timeSchedStart.Minutes) % timeIncrement;
                if (minsOver > 0)
                {
                    int minsToAdd = timeIncrement - minsOver;
                    timeSchedStart = timeSchedStart.Add(new TimeSpan(0, minsToAdd, 0));
                }
                //Double check that we haven't pushed the start time past the stop time.
                if (timeSchedStart >= timeSchedStop)
                {
                    continue;
                }
                //Figure out all possible operatories for this particular schedule.
                List <Operatory> listOpsForSchedule = new List <Operatory>();
                if (schedule.Ops.Count > 0)
                {
                    listOpsForSchedule = listOperatories.FindAll(x => schedule.Ops.Exists(y => y == x.OperatoryNum));
                }
                else                  //Dynamic schedule.  Figure out what operatories this provider is part of that are associated to the corresponding eService.
                                      //Get all of the valid operatories that this provider is associated with.
                {
                    listOpsForSchedule = listOperatories.FindAll(x => x.ProvDentist == schedule.ProvNum || x.ProvHygienist == schedule.ProvNum);
                }
                if (PrefC.HasClinicsEnabled)
                {
                    //Skip this schedule entry if the operatory's clinic does not match the patient's clinic.
                    if (clinic == null)
                    {
                        //If a clinic was not passed in, ONLY consider unassigned operatories
                        listOpsForSchedule = listOpsForSchedule.FindAll(x => x.ClinicNum == 0);
                    }
                    else
                    {
                        //If a valid clinic was passed in, make sure the operatory has a matching clinic.
                        listOpsForSchedule = listOpsForSchedule.FindAll(x => x.ClinicNum == clinic.ClinicNum);
                    }
                }
                if (listOpsForSchedule.Count == 0)
                {
                    continue;                    //No valid operatories for this schedule.
                }
                log?.WriteLine("schedule: " + schedule.ScheduleNum + "\tlistOpsForSchedule:\r\n\t"
                               + string.Join(",\r\n\t", listOpsForSchedule.Select(x => x.OperatoryNum + " - " + x.Abbrev)), LogLevel.Verbose);
                //The list of operatories has been filtered above so we need to find ALL available time slots for this schedule in all operatories.
                foreach (Operatory op in listOpsForSchedule)
                {
                    AddTimeSlotsFromSchedule(listAvailableTimeSlots, schedule, op.OperatoryNum, timeSchedStart, timeSchedStop
                                             , listBlockoutSchedules, dictProvSchedules, listApptsForOps, timePattern, defNumApptType, isDoubleBookingAllowed);
                }
            }
            //Remove any time slots that start before right now (just in case the consuming method is looking for slots for today).
            listAvailableTimeSlots.RemoveAll(x => x.DateTimeStart.Date == DateTime.Now.Date && x.DateTimeStart.TimeOfDay < DateTime.Now.TimeOfDay);
            //Order the entire list of available time slots so that they are displayed to the user in sequential order.
            //We need to do this because we loop through each provider's schedule one at a time and add openings as we find them.
            //Then order by operatory.ItemOrder in order to preserve old behavior (filling up the schedule via operatories from the left to the right).
            return(listAvailableTimeSlots.OrderBy(x => x.DateTimeStart)
                   //listOpNums was ordered by ItemOrder at the top of this method so we can trust that it is in the correct order.
                   .ThenBy(x => listOpNums.IndexOf(x.OperatoryNum))
                   .ToList());
        }
Пример #10
0
        private void timer1_Tick(object sender, EventArgs e)
        {   //zegar
            timee     = timee.Add(TimeSpan.FromMilliseconds(speed));
            time.Text = string.Format("{0}:{1}", timee.Minutes, timee.Seconds);

            //Snake
            if (Up)
            {
                snake.MoveUp();
            }

            if (Down)
            {
                snake.MoveDown();
            }

            if (Right)
            {
                snake.MoveRight();
            }

            if (Left)
            {
                snake.MoveLeft();
            }

            //ClientSnake
            if (Cup)
            {
                clientSnake.MoveUp();
            }

            if (Cdown)
            {
                clientSnake.MoveDown();
            }

            if (Cright)
            {
                clientSnake.MoveRight();
            }

            if (Cleft)
            {
                clientSnake.MoveLeft();
            }

            //speed
            if (ScoreQuantity1 == 10 || ScoreQuantity2 == 10)
            {
                speed           = 200;
                timer1.Interval = speed;
            }
            if (ScoreQuantity1 == 20 || ScoreQuantity2 == 20)
            {
                speed           = 150;
                timer1.Interval = speed;
            }
            if (ScoreQuantity1 == 30 || ScoreQuantity2 == 30)
            {
                speed           = 100;
                timer1.Interval = speed;
            }
            if (ScoreQuantity1 == 40 || ScoreQuantity2 == 40)
            {
                speed           = 50;
                timer1.Interval = speed;
            }

            this.Invalidate();
            Collision();
            Eat();
        }
Пример #11
0
        /// <summary>
        /// Creates a new plan nad sets bPlanHasChanged to true
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="GameLength"></param>
        /// <param name="GamePause">Pause zwischen den Spielen</param>
        /// <param name="lPauses">Liste mit unregelmäßigen Pausen</param>
        /// <param name="lTeams"><see cref="KeyValuePair"/> mit Team und einem bool ob es in der Wertung ist</param>
        /// <returns></returns>
        private List <Spiele> makePlan(string StartTime, int GameLength, int GamePause, List <Tuple <string, int> > lPauses, List <KeyValuePair <string, bool> > lTeams)
        {
            if (lTeams == null || StartTime == "" || GameLength == -1 || GamePause == -1 || lPauses == null)
            {
                return(new List <Spiele>());
            }

            //Formate testen
            if (!Regex.IsMatch(StartTime, @"^\d{2}:\d{2}$"))
            {
                return(new List <Spiele>());
            }

            bool isOdd = mod(lTeams.Count, 2) == 0 ? false : true;

            TimeSpan startTime = TimeSpan.Parse(StartTime);

            List <string> Teams = new List <string>();

            foreach (var s in lTeams)
            {
                Teams.Add(s.Key);
            }

            if (isOdd)
            {
                Teams.Add("TEMP");
            }

            List <Game> GamePlan = new List <Game>();
            int         c        = Teams.Count;

            //Spielplan nach Round-Robin system
            for (int i = 1; i < c; i++)
            {
                GamePlan.Add(new Game {
                    Guest = Teams[i - 1], Home = Teams[c - 1]
                });

                for (int k = 1; k < (Teams.Count / 2); k++)
                {
                    GamePlan.Add(new Game
                    {
                        Guest = Teams[mod((i + k), (c - 1)) != 0 ? mod((i + k), (c - 1)) - 1 : c - 2],
                        Home  = Teams[mod((i - k), (c - 1)) != 0 ? mod((i - k), (c - 1)) - 1 : c - 2]
                    });
                }
            }

            if (isOdd)
            {
                GamePlan.RemoveAll(a => a.Home == "TEMP" || a.Guest == "TEMP");
            }

            List <Spiele> sp = new List <Spiele>();

            int pause = GamePause;
            int dauer = GameLength;
            int count = 0;

            foreach (var s in GamePlan)
            {
                sp.Add(new Spiele
                {
                    Id         = count,
                    Time       = string.Format(startTime.ToString(@"hh\:mm") + " - " + startTime.Add(TimeSpan.FromMinutes(dauer)).ToString(@"hh\:mm")),
                    Home       = s.Home,
                    Guest      = s.Guest,
                    GuestGoals = -1,
                    HomeGoals  = -1,
                    Played     = false,
                    Rating     = lTeams.Where(a => a.Key == s.Home).FirstOrDefault().Value == true && lTeams.Where(a => a.Key == s.Guest).FirstOrDefault().Value == true ? true : false
                });

                startTime = startTime.Add(TimeSpan.FromMinutes(dauer + pause));

                if (lPauses.Count > 0)
                {
                    foreach (var l in lPauses)
                    {
                        string zeit  = l.Item1.ToString();
                        string länge = l.Item2.ToString();

                        TimeSpan tres = TimeSpan.Parse(zeit);
                        TimeSpan t    = tres.Add(TimeSpan.FromMinutes(int.Parse(länge)));

                        if ((tres <= startTime && startTime <= t) || (tres <= startTime.Add(TimeSpan.FromMinutes(dauer)) && startTime.Add(TimeSpan.FromMinutes(dauer)) <= t))
                        {
                            startTime = t;
                        }
                    }
                }
                count++;
            }
            bPlanHasChanged = true;
            return(sp);
        }
Пример #12
0
 public void should_equal_to_another_instance_of_time_to_live_which_valid_for_the_same_period_of_time()
 {
     timeToLive.Should().Be(TimeToLive.CreateValidFor(validFor));
     timeToLive.Should().NotBe(TimeToLive.CreateValidFor(validFor.Add(TimeSpan.FromMinutes(1))));
 }
Пример #13
0
        private List <v_Movie> GetListInternal(string actressName, int?isLiked)
        {
            //播放量字典
            Dictionary <string, DataValue> dict = this.GetViewCountDict();
            string movieServer = _configuration.GetValue <string>("movieServer");

            List <v_Movie> LsMovies    = new List <v_Movie>();
            var            dirs        = new DirectoryInfo(movieRootPath).GetDirectories();
            var            actressDirs = string.IsNullOrEmpty(actressName) ? dirs : dirs.Where(y => y.Name.Contains(actressName));

            foreach (var actressItem in actressDirs) //每女优
            {
                v_Actress actress = new v_Actress();
                actress.FullName = actressItem.Name;
                var actressFiles = actressItem.GetFiles();// 获取女优图片
                foreach (var photoItem in actressFiles)
                {
                    string picRelativePath = photoItem.FullName.Replace(movieRootPath, "");
                    string path            = movieServer + picRelativePath?.Replace("\\", "/");
                    actress.Portraits.Add(path);
                    if (string.IsNullOrEmpty(actress.Cover))
                    {
                        actress.Cover = path;
                    }
                }
                var fanHaoDirs = actressItem.GetDirectories(); //所有番号 文件夹
                foreach (var fanHaoItem in fanHaoDirs)
                {
                    TimeSpan _totalTime  = new TimeSpan();
                    var      fanHaoFiles = fanHaoItem.GetFiles();
                    string   FanHaoRaw   = fanHaoItem.Name;
                    string   FanHao      = fanHaoItem.Name.TrimEnd("-C".ToCharArray());
                    v_Movie  movie       = new v_Movie();
                    foreach (var item in fanHaoFiles)
                    {
                        var ext = item.Extension;
                        if (ext == ".mp4" || ext == ".webm") //视频
                        {
                            var Source = movieServer + item.FullName.Replace(movieRootPath, "")?.Replace("\\", "/");
                            movie.Sources.Add(Source);
                            VideoEncoder.VideoFile videoFile = null;
                            if (!dict.Keys.Any(x => x == FanHao))
                            {
                                int row = SQLiteHelper.ExecuteNonQuery($"INSERT INTO Dict ( DataKey,DataValue) VALUES ('{FanHao}','0');");
                                dict.Add(FanHao, new DataValue()
                                {
                                    LastAccessTime = DateTime.Now
                                });
                            }
                            bool isffmpeg = dict[FanHao].TotalTime == "0";
                            if (isffmpeg)
                            {
                                VideoEncoder.Encoder enc = new VideoEncoder.Encoder();
                                //ffmpeg.exe的路径,程序会在执行目录(....FFmpeg测试\bin\Debug)下找此文件,
                                enc.FFmpegPath = "ffmpeg.exe";
                                //视频路径
                                videoFile = new VideoEncoder.VideoFile(item.FullName);
                                enc.GetVideoInfo(videoFile);
                                _totalTime = _totalTime.Add(videoFile.Duration); //总时长
                                int row = SQLiteHelper.ExecuteNonQuery($"UPDATE Dict SET TotalTime='{string.Format("{0:00}:{1:00}:{2:00}", (int)_totalTime.TotalHours, _totalTime.Minutes, _totalTime.Seconds)}' WHERE DataKey = '{FanHao}'; ");
                            }
                            else
                            {
                                if (dict.Any(x => x.Key == FanHao))
                                {
                                    TimeSpan.TryParse(dict[FanHao].TotalTime, out TimeSpan t);
                                    _totalTime = t;
                                }
                                else
                                {
                                    _totalTime = new TimeSpan();
                                }
                            }
                            if (!LsMovies.Contains(movie))
                            {
                                movie.Id             = LsMovies.Count + 1;
                                movie.FanHao         = FanHao;
                                movie.Date           = item.CreationTime.ToString("yyyy-MM-dd HH:mm");
                                movie.CreationTime   = item.CreationTime;
                                movie.PostedDate     = this.FormatPostedDate(item.CreationTime);
                                movie.LastAccessTime = dict.Any(x => x.Key == FanHao) ? dict[FanHao].LastAccessTime :DateTime.Now;
                                movie.LastAccess     = movie.LastAccessTime.ToString("yyyy-MM-dd HH:mm:ss");
                                movie.ViewCount      = dict.Any(x => x.Key == FanHao) ? dict[FanHao].count : 0;
                                movie.IsLiked        = dict.Any(x => x.Key == FanHao) ? dict[FanHao].isLiked : 0;
                                movie.Actress        = actress;
                                if (isffmpeg)
                                {
                                    //mpeg信息
                                    movie.Height            = videoFile.Height;
                                    movie.Width             = videoFile.Width;
                                    movie.DisPlayResolution = videoFile.Width + "x" + videoFile.Height;
                                    int row = SQLiteHelper.ExecuteNonQuery($"UPDATE Dict SET Height='{videoFile.Height}',Width='{videoFile.Width}' WHERE DataKey = '{FanHao}'; ");
                                }
                                else
                                {
                                    movie.Height            = dict[FanHao].Height;
                                    movie.Width             = dict[FanHao].Width;
                                    movie.DisPlayResolution = movie.Width + "x" + movie.Height;
                                }
                                LsMovies.Add(movie);
                            }
                            movie.TotalTime = string.Format("{0:00}:{1:00}:{2:00}", (int)_totalTime.TotalHours, _totalTime.Minutes, _totalTime.Seconds);
                            movie.Duration  = _totalTime;

                            // //FileInfo fi = new FileInfo(item.FullName); //xx/xx/aa.rar
                            // var rnj= fanHaoFiles.Where(x =>Path.GetExtension( x.Name) == ".jpg" && x.Name.Contains(FanHao)).FirstOrDefault();
                            // //fi.MoveTo(Path.GetFileNameWithoutExtension(rnj.FullName) + ".mp4"); //xx/xx/xx.rar
                            // if(rnj != null)
                            // {
                            //     if(item.FullName.EndsWith("-A.mp4") || item.FullName.EndsWith("-B.mp4"))
                            //     {
                            //         Console.WriteLine( "$AB集$  " + item.FullName );
                            //     }
                            //     else
                            //     {
                            //         if(FanHaoRaw.EndsWith("-C"))
                            //         {
                            //             Computer MyComputer = new Computer();
                            //             string newName = FanHaoRaw + Path.GetFileNameWithoutExtension(rnj.FullName).Replace(FanHaoRaw, "").Replace(FanHao, "") + ".mp4";
                            //             MyComputer.FileSystem.RenameFile(item.FullName, newName);
                            //             string newJpgName = newName.Replace(".mp4", "") + ".jpg";
                            //             MyComputer.FileSystem.RenameFile(rnj.FullName, newJpgName);
                            //             Console.WriteLine( "#中文#  " + item.FullName + " => " + newName);
                            //             Console.WriteLine( "#中文图片#  " + rnj.FullName + " => " + newJpgName);
                            //         }
                            //         else
                            //         {
                            //             Computer MyComputer = new Computer();
                            //             string newName = Path.GetFileNameWithoutExtension(rnj.FullName) + ".mp4";
                            //             MyComputer.FileSystem.RenameFile(item.FullName, newName);
                            //             Console.WriteLine( item.FullName + " => " + newName);
                            //         }
                            //     }


                            // }
                            // else
                            // {
                            //     Console.WriteLine("[失败]" + item.FullName);
                            // }
                        }
                        if (ext == ".jpg" || ext == ".png") //图片
                        {
                            string picRelativePath = item.FullName.Replace(movieRootPath, "")?.Replace("\\", "/");

                            if (item.Name.Contains(FanHao))
                            {
                                movie.Title = Path.GetFileNameWithoutExtension(item.Name);
                                movie.Cover = movieServer + picRelativePath;
                            }
                            else
                            {
                                movie.Preview.Add(movieServer + picRelativePath);
                            }
                        }
                    }
                }
            }
            //默认值
            foreach (var item in LsMovies)
            {
                if (item.Cover == null)
                {
                    continue;
                }
                if (!item.Cover.Contains(".jpg")) //视频不包含图片添加默认图片
                {
                    item.Cover = "../images/default.jpg";
                }
            }
            //是否喜欢条件
            LsMovies = isLiked == null ? LsMovies : LsMovies.Where(x => x.IsLiked == isLiked.GetValueOrDefault()).ToList();
            _memoryCache.Set("movieTempList", LsMovies, new MemoryCacheEntryOptions()
                             .SetAbsoluteExpiration(TimeSpan.FromMinutes(30)));
            return(LsMovies);
        }
Пример #14
0
 public static TimeSpan TrimMilliseconds(this TimeSpan self)
 {
     return(self.Add(TimeSpan.FromMilliseconds(-self.Milliseconds)));
 }
Пример #15
0
        private double getTienTangCaCaDem()
        {
            //          YS2
            // 7h30 PM - 10h PM= 100%.
            // 10h PM -> 3:30 AM: 130%.
            // 3h30 AM -> 6h AM: 215%.
            // 6h -> DenGio = 150%.
            //          YSS
            // 8h PM - 10h PM= 100%.
            // 10h PM -> 4h AM: 130%.
            // 4h AM -> 6h AM: 215%.
            // 6h -> DenGio = 150%.
            double total = 0;

            if (_kq.tgTinhTangCa > 0)
            {
                TimeSpan tgBatDauTinhTC = _kq.tuGio.Add(_kq.denGio);
                if (tgBatDauTinhTC.Days >= 1)
                {
                    tgBatDauTinhTC = tgBatDauTinhTC.Add(new TimeSpan(tgBatDauTinhTC.Days * -1, 0, 0, 0));
                }

                double soGioTangCa = _kq.tgTinhTangCa;
                if (_kq.tgTinhTangCa == 1.9)
                {
                    soGioTangCa = 2;
                }
                if (_kq.ngay.DayOfWeek == DayOfWeek.Sunday) // Nếu là chủ nhật
                {
                    for (double tg = 0.5; tg <= soGioTangCa;)
                    {
                        tgBatDauTinhTC = tgBatDauTinhTC.Add(new TimeSpan(0, 30, 0)); // Mỗi lần tăng 0.5 thì + 30ph.
                        if (tgBatDauTinhTC <= new TimeSpan(3, 30, 0))
                        {
                            total += _LuongTungNgay / 8 * 0.5 * 270 / 100; // 10h PM -> 4:00 AM: 270%.
                        }
                        else if (tgBatDauTinhTC <= new TimeSpan(6, 0, 0))
                        {
                            total += _LuongTungNgay / 8 * 0.5 * 200 / 100; // 4h AM -> 6h AM: 200%.
                        }
                        else if (tgBatDauTinhTC <= new TimeSpan(11, 00, 0))
                        {
                            total += _LuongTungNgay / 8 * 0.5 * 150 / 100; //6h AM -> DenGio = 150%.
                        }
                        tg += 0.5;
                    }
                }
                else // Nếu là ngày thường
                {
                    for (double tg = 0.5; tg <= soGioTangCa;)
                    {
                        tgBatDauTinhTC = tgBatDauTinhTC.Add(new TimeSpan(0, 30, 0)); // Mỗi lần tăng 0.5 thì + 30ph.
                        if (tgBatDauTinhTC <= new TimeSpan(3, 30, 0))
                        {
                            total += _LuongCB1Ngay / 8 * 0.5 * 130 / 100; // 10h PM -> 3h30 AM: 130%.
                        }
                        else if (tgBatDauTinhTC <= new TimeSpan(6, 0, 0))
                        {
                            total += _LuongCB1Ngay / 8 * 0.5 * 215 / 100; // 3h30 AM -> 6h AM: 215%.
                        }
                        else if (tgBatDauTinhTC <= new TimeSpan(11, 00, 0))
                        {
                            total += _LuongCB1Ngay / 8 * 0.5 * 150 / 100; //6h AM -> DenGio: 150%.
                        }
                        tg += 0.5;
                    }
                }
                return(total);
            }
            else
            {
                return(0); // Nếu k có TangCa thì trả về 0.
            }
        }
Пример #16
0
        public void ParsingBlockingVsNonBlocking3()
        {
            this.EnsureNIOData();

            Stopwatch timer = new Stopwatch();
            TimeSpan  blockingTime = new TimeSpan(), nonBlockingTime = new TimeSpan();

            int maxSize = 1024 * 32;

            for (int size = 1024; size < maxSize; size += 1024)
            {
                Console.WriteLine("Buffer Size " + size);
                for (int i = 0; i < 25; i++)
                {
                    timer.Reset();

                    //Test Blocking
                    BlockingTextReader blocking = ParsingTextReader.CreateBlocking(File.OpenText("resources\\nio.ttl"), 4096);
                    timer.Start();
                    int totalBlocking = 0;
                    int read;
                    while (!blocking.EndOfStream)
                    {
                        read = blocking.Read();
                        if (read >= 0)
                        {
                            totalBlocking++;
                        }
                    }
                    timer.Stop();
                    blocking.Close();
                    blockingTime = blockingTime.Add(timer.Elapsed);

                    //Reset
                    timer.Reset();
                    int totalNonBlocking = 0;

                    NonBlockingTextReader nonBlocking = ParsingTextReader.CreateNonBlocking(File.OpenText("resources\\nio.ttl"), 4096);
                    timer.Start();
                    while (!nonBlocking.EndOfStream)
                    {
                        read = nonBlocking.Read();
                        if (read >= 0)
                        {
                            totalNonBlocking++;
                        }
                    }
                    timer.Stop();
                    nonBlocking.Close();
                    nonBlockingTime = nonBlockingTime.Add(timer.Elapsed);

                    Assert.Equal(totalBlocking, totalNonBlocking);
                }

                Console.WriteLine();
                Console.WriteLine("Blocking Total Time = " + blockingTime);
                Console.WriteLine("Non-Blocking Total Time = " + nonBlockingTime);
                Console.WriteLine();
                blockingTime    = new TimeSpan();
                nonBlockingTime = new TimeSpan();
            }
        }
Пример #17
0
        static ArrayList timeslots = new ArrayList();        // declaring timeslots as static arraylist

        protected void Page_Load(object sender, EventArgs e) //page load
        {
            if (!this.IsPostBack)
            {
                countSelected = 0;
            }

            if (Session["field1"] != null)//checking if session feild is not null
            {
                //retrieving the break start time from the database
                TimeSpan      breakStartTime = new TimeSpan();
                SqlConnection breakStart_con = new SqlConnection("Data Source=ict333server.database.windows.net;Initial Catalog=database-tmd;User ID=ondopher;Password=Murdoch2016"); // sql connection string to database
                breakStart_con.Open();                                                                                                                                                // opening the sql connection
                SqlCommand    breakStart_cmd  = new SqlCommand("Select * from Series Where Series_ID = '" + (int)Session["SID"] + "'", breakStart_con);                               // sql query to select meeting break start and end times for this particular session
                SqlDataReader read_breakStart = breakStart_cmd.ExecuteReader();                                                                                                       //sql data reader to get the break start time of meeting
                while (read_breakStart.Read())                                                                                                                                        //opening sql data reader
                {
                    breakStartTime = (TimeSpan)read_breakStart["Lunch_Break_Start"];                                                                                                  //read in time as a TimeSpan
                }

                breakStart_con.Close();


                //retrieving the break end time from the database
                TimeSpan      breakEndTime = new TimeSpan();
                SqlConnection breakEnd_con = new SqlConnection("Data Source=ict333server.database.windows.net;Initial Catalog=database-tmd;User ID=ondopher;Password=Murdoch2016"); // sql connection string to database
                breakStart_con.Open();                                                                                                                                              // opening the sql connection
                SqlCommand    breakEnd_cmd  = new SqlCommand("Select * from Series Where Series_ID = '" + (int)Session["SID"] + "'", breakEnd_con);                                 // sql query to select meeting break start and end times for this particular session
                SqlDataReader read_breakEnd = breakStart_cmd.ExecuteReader();                                                                                                       //sql data reader to get the break start time of meeting
                while (read_breakEnd.Read())                                                                                                                                        //opening sql data reader
                {
                    breakEndTime = (TimeSpan)read_breakEnd["Lunch_Break_End"];                                                                                                      //read in time as a TimeSpan
                }

                breakEnd_con.Close();

                //retrieving the meeting duration from the database
                Int32         Duration = 0;                                                                                                                                     // declaring duration as integer, intial value is 0
                SqlConnection am       = new SqlConnection("Data Source=ict333server.database.windows.net;Initial Catalog=database-tmd;User ID=ondopher;Password=Murdoch2016"); //my connection string to database
                am.Open();                                                                                                                                                      //opening my sql connection
                SqlCommand    cmd_sub   = new SqlCommand("Select  Meeting_Duration from Series Where Series_ID = '" + (int)Session["SID"] + "'", am);                           // my sql query to select meeting duration
                SqlDataReader read_data = cmd_sub.ExecuteReader();                                                                                                              //my sql data reader to get the duration of meeting
                while (read_data.Read())                                                                                                                                        //opening sql data reader
                {
                    Duration = read_data.GetInt32(0);                                                                                                                           //storing duration in string "duration"
                }



                //declaring my time spans
                TimeSpan start     = new TimeSpan(9, 0, 0);
                TimeSpan end       = new TimeSpan(22, 0, 0);
                TimeSpan increment = new TimeSpan(0, Duration, 0);


                while (start <= end)                                                                   //while loop to create time slots
                {
                    if ((start.CompareTo(breakStartTime) < 0) || (start.CompareTo(breakEndTime) >= 0)) //if statment to add lunch break
                    {
                        if ((breakStartTime - start).CompareTo(increment) == (breakStartTime.CompareTo(start)))
                        {
                            cblist.Items.Add(new ListItem(start.ToString())); //adding timeslots to my checkbox list
                            cblist.RepeatColumns = 4;
                        }
                    }

                    start = start.Add(increment);// declaring duration as my new start
                }

                PlaceHolder1.Controls.Add(cblist);                                                                                                                         // adding timeslots to a placeholder
                am.Close();                                                                                                                                                //closing sql connection
                SqlConnection con = new SqlConnection("Data Source=ict333server.database.windows.net;Initial Catalog=database-tmd;User ID=ondopher;Password=Murdoch2016"); //new sql connection
                con.Open();                                                                                                                                                //opening new sql connection
                SqlCommand    AIDCOUNT   = new SqlCommand("Select  count(Attendee_ID) from Attendee Where Series_ID = '" + (int)Session["SID"] + "'", con);                // sql query to count number of attendees in current series
                SqlDataReader read_data1 = AIDCOUNT.ExecuteReader();                                                                                                       //data reader for counting number of attendees in current series
                while (read_data1.Read())                                                                                                                                  // opening my data reader
                {
                    MinSlot     = read_data1.GetInt32(0);                                                                                                                  // storing the attendee count in integer
                    mslots.Text = Convert.ToString(MinSlot);                                                                                                               //converting the attendee count to string
                }
                read_data1.Close();                                                                                                                                        //closing my data reader
                con.Close();                                                                                                                                               //closing my sql connection
            }
            else
            {
                Response.Redirect("login.aspx");//if login session is cleared the system redirects to login page
            }
        }
Пример #18
0
        ///<summary>Adds valid time slots to listAvailableTimeSlots if the time slot found does NOT already exist within the list.
        ///This is a helper method to better break up the complexity of GetAvailableWebSchedTimeSlots() so that it is easier to follow.
        ///Make sure that timePattern is always passed in utilizing 5 minute increments (no conversion will be applied to the pattern passed in).
        ///Optionally set defNumApptType if looking for time slots for New Pat Appt which will apply the DefNum to all time slots found.</summary>
        private static void AddTimeSlotsFromSchedule(List <TimeSlot> listAvailableTimeSlots, Schedule schedule, long operatoryNum
                                                     , TimeSpan timeSchedStart, TimeSpan timeSchedStop, List <Schedule> listBlockouts
                                                     , Dictionary <DateTime, List <ApptSearchProviderSchedule> > dictProvSchedules, List <Appointment> listApptsForOps, string timePattern
                                                     , long defNumApptType = 0, bool isDoubleBookingAllowed = true)
        {
            //No need to check RemotingRole; no call to db and this is a private method.
            //Figure out how large of a time slot we need to find in order to consider this time slot "available".
            int      apptLengthMins = timePattern.Length * 5;
            int      timeIncrement  = PrefC.GetInt(PrefName.AppointmentTimeIncrement);
            DateTime dateSched      = schedule.SchedDate;
            //Filter out all blockouts that are not pertinent to this dateSched and operatoryNum combo.
            List <Schedule> listBlockoutsForDateAndOp = listBlockouts.FindAll(x => x.SchedDate.Date == dateSched.Date && x.Ops.Contains(operatoryNum));
            //Filter out all appointments that are not pertinent to this dateSched and operatoryNum combo.
            List <Appointment> listApptsForDateAndOp = listApptsForOps.FindAll(x => x.AptDateTime.Date == dateSched.Date && x.Op == operatoryNum);
            //Start going through this operatory's schedule according to the time increment, looking for a gap that can handle apptLengthMins.
            TimeSpan timeSlotStart = new TimeSpan(timeSchedStart.Ticks);
            //Make a list of all perfect world appointment starting times that we will use within our time slot finding loop to make our slot finding
            //more predictable and user friendly.  This is mainly for the scenario where offices manually schedule strange appointments throughout the day.
            //E.g. Searching for hour long time slots, a 15 min appt was manually scheduled for 09:55 - 10:10 which throws off the nice "on the hour" slots.
            //We want to have logic that will prefer to return time slots on the hour.  E.g. 8 - 9, 10:10 - 11: 10, 11 - 12 (note the overlap), 12 - 13...
            List <TimeSpan> listPerfectSlotStarts = new List <TimeSpan>();

            //The first perfect time slot start will always be when our schedule starts.
            for (TimeSpan timeSlotPerfect = new TimeSpan(timeSchedStart.Ticks)
                 ; timeSlotPerfect <= new TimeSpan(timeSchedStop.Ticks)
                 ; timeSlotPerfect = timeSlotPerfect.Add(new TimeSpan(0, apptLengthMins, 0)))
            {
                listPerfectSlotStarts.Add(timeSlotPerfect);
            }
            //Start looking for collisions AFTER the start time.
            //Stop as soon as the slots stop time meets or passes the sched stop time.
            //Iterate through the schedule via the time increment preference.
            for (TimeSpan timeSlotStop = timeSchedStart.Add(new TimeSpan(0, timeIncrement, 0))
                 ; timeSlotStop <= timeSchedStop
                 ; timeSlotStop = timeSlotStop.Add(new TimeSpan(0, timeIncrement, 0)))
            {
                //Check to see if we've found an opening.
                TimeSpan timeSpanCur = timeSlotStop - timeSlotStart;
                //Check to see if there is an appointment or a blockout that collides with this blockout.
                bool isOverlapping = false;
                #region Blockout Collisions
                TimeSpan timeBlockoutStart = new TimeSpan();
                TimeSpan timeBlockoutStop  = new TimeSpan();
                //First we'll look at blockouts because it should be quicker than looking at the appointments
                foreach (Schedule blockout in listBlockoutsForDateAndOp)
                {
                    //Create new TimeSpans in order to remove the date portion from the blockouts.
                    timeBlockoutStart = new TimeSpan(blockout.StartTime.Hours, blockout.StartTime.Minutes, 0);
                    timeBlockoutStop  = new TimeSpan(blockout.StopTime.Hours, blockout.StopTime.Minutes, 0);
                    if (IsTimeOverlapping(timeSlotStart, timeSlotStop, timeBlockoutStart, timeBlockoutStop))
                    {
                        isOverlapping = true;
                        break;
                    }
                }
                if (isOverlapping)                 //This check is here so that we don't waste time looping through appointments if we don't need to.
                //There was a collision with a blockout.  Set the time slot start time to the stop time of the blockout and continue from there.
                {
                    timeSlotStart = timeBlockoutStop;
                    continue;
                }
                #endregion
                #region Appointment Collisions
                TimeSpan timeApptStart = new TimeSpan();
                TimeSpan timeApptStop  = new TimeSpan();
                //Next we'll look for overlapping appointments
                foreach (Appointment appointment in listApptsForDateAndOp)
                {
                    timeApptStart = appointment.AptDateTime.TimeOfDay;
                    timeApptStop  = appointment.AptDateTime.AddMinutes(appointment.Pattern.Length * 5).TimeOfDay;
                    if (IsTimeOverlapping(timeSlotStart, timeSlotStop, timeApptStart, timeApptStop))
                    {
                        isOverlapping = true;
                        break;
                    }
                }
                if (isOverlapping)
                {
                    //There was a collision with an appointment.  Set the time slot start time to the stop time of the appointment and continue from there.
                    timeSlotStart = timeApptStop;
                    continue;
                }
                #endregion
                #region Opening Found
                if (timeSpanCur.TotalMinutes >= apptLengthMins)
                {
                    //We just found an opening.  Make sure we don't already have this time slot available.
                    DateTime dateTimeSlotStart = new DateTime(dateSched.Year, dateSched.Month, dateSched.Day, timeSlotStart.Hours, timeSlotStart.Minutes, 0);
                    DateTime dateTimeSlotStop  = new DateTime(dateSched.Year, dateSched.Month, dateSched.Day, timeSlotStop.Hours, timeSlotStop.Minutes, 0);
                    TimeSlot timeSlot          = new TimeSlot(dateTimeSlotStart, dateTimeSlotStop, operatoryNum, schedule.ProvNum, defNumApptType);
                    if (!listAvailableTimeSlots.Any(x => (x.DateTimeStart == dateTimeSlotStart && x.DateTimeStop == dateTimeSlotStop &&
                                                          x.ProvNum == schedule.ProvNum))) //We will return multiple time slots for the same time for different providers.
                    {
                        //This time slot is not already in our list of available time slots, check for double booking.
                        if (dictProvSchedules.ContainsKey(dateSched.Date))
                        {
                            long recallProvNum = schedule.ProvNum;
                            if (IsApptTimeSlotDoubleBooked(dictProvSchedules[dateSched.Date], listApptsForDateAndOp, recallProvNum, timePattern, dateTimeSlotStart
                                                           , defNumApptType, isDoubleBookingAllowed))
                            {
                                //There is a double booking conflict.  Do not add this time slot as a possibility.
                                //However, at this point we know that there are no appointment conflicts for the current time slot, only a double booking conflict.
                                //The appointment needs to scoot within the operatory to hopefully find the first available opening (unit test 86).
                                timeSlotStart = timeSlotStart.Add(new TimeSpan(0, timeIncrement, 0));
                                continue;
                            }
                        }
                        //There are no collisions with this provider's schedule, add it to our list of available time slots.
                        listAvailableTimeSlots.Add(timeSlot);
                        //Check to see if the time slot that was just added started on a "perfect starting time".
                        //If it didn't, we need to backtrack to the most recent "perfect starting time" and continue from there.
                        if (!listPerfectSlotStarts.Contains(timeSlotStart))
                        {
                            //Find the most recent "perfect starting time" that corresponds to the timeSlotStop that was just found.
                            //We then need to set both timeSlotStart AND timeSlotStop to the closest "perfect starting time" and continue from there.
                            //E.g. If apptLengthMins is 60 minutes, odds are we are looking for appointments that start on the hour.
                            //So if we just found an opening that started at 10:10 then we need to backtrack from the stopping time of 11:10 and find the closest
                            //"perfect starting time", 11:00 in this case, and continue searching from there.
                            timeSlotStart = listPerfectSlotStarts.Last(x => x.Subtract(timeSlotStop).TotalMinutes < 0);
                            timeSlotStop  = timeSlotStart;
                        }
                    }
                    else
                    {
                        //We have found a time slot in another operatory that matches the necessary criteria.
                        //Check to see if this operatory should be considered before the previously found operatory.
                        TimeSlot  timeSlotCur  = listAvailableTimeSlots.First(x => (x.DateTimeStart == dateTimeSlotStart && x.DateTimeStop == dateTimeSlotStop));
                        Operatory operatoryIn  = Operatories.GetOperatory(operatoryNum);
                        Operatory operatoryCur = Operatories.GetOperatory(timeSlotCur.OperatoryNum);
                        if (operatoryIn.ItemOrder < operatoryCur.ItemOrder)
                        {
                            timeSlotCur.OperatoryNum = operatoryIn.OperatoryNum;
                        }
                    }
                    //Continue looking for more open slots starting at the end of this time slot.
                    //E.g. we just found 9:30 AM to 10:00 AM.  We need to continue from 10:00 AM.
                    timeSlotStart = timeSlotStop;
                    continue;
                }
                #endregion
            }
        }
Пример #19
0
    public virtual bool runTest()
    {
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Console.Error.WriteLine(strName + ": " + strTest + " runTest started...");
        TimeSpan ts1;
        TimeSpan ts2;
        TimeSpan tsSum;

        do
        {
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Add a positive hour to TimeSpan object");
            try
            {
                ts1   = new TimeSpan(TimeSpan.TicksPerHour);
                ts2   = new TimeSpan(TimeSpan.TicksPerHour);
                tsSum = ts1.Add(ts2);
                if (tsSum.Ticks != 2 * TimeSpan.TicksPerHour)
                {
                    String strInfo = strTest + " error: ";
                    strInfo = strInfo + "Expected Ticks <" + 2 * TimeSpan.TicksPerHour + "> ";
                    strInfo = strInfo + "Returned Ticks <" + tsSum.Ticks + "> ";
                    Console.WriteLine(strTest + "E_101a: " + strInfo);
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_10001: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Add a negative hour to TimeSpan object");
            try
            {
                ts1   = new TimeSpan(3 * TimeSpan.TicksPerHour);
                ts2   = new TimeSpan(-TimeSpan.TicksPerHour);
                tsSum = ts1.Add(ts2);
                if (tsSum.Ticks != 2 * TimeSpan.TicksPerHour)
                {
                    String strInfo = strTest + " error: ";
                    strInfo = strInfo + "Expected Ticks <" + 2 * TimeSpan.TicksPerHour + "> ";
                    strInfo = strInfo + "Returned Ticks <" + tsSum.Ticks + "> ";
                    Console.WriteLine(strTest + "E_202a: " + strInfo);
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_20202: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
            ++iCountTestcases;
            Console.Error.WriteLine("[]  Add zero time to TimeSpan object");
            try
            {
                ts1   = new TimeSpan(2 * TimeSpan.TicksPerHour);
                ts2   = new TimeSpan(0);
                tsSum = ts1.Add(ts2);
                if (tsSum.Ticks != 2 * TimeSpan.TicksPerHour)
                {
                    String strInfo = strTest + " error: ";
                    strInfo = strInfo + "Expected Ticks <" + 2 * TimeSpan.TicksPerHour + "> ";
                    strInfo = strInfo + "Returned Ticks <" + tsSum.Ticks + "> ";
                    Console.WriteLine(strTest + "E_202a: " + strInfo);
                    ++iCountErrors;
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(strTest + "E_20202: Unexpected Exception: " + ex.ToString());
                ++iCountErrors;
                break;
            }
        }while (false);
        Console.Error.Write(strName);
        Console.Error.Write(": ");
        if (iCountErrors == 0)
        {
            Console.Error.WriteLine(strTest + " iCountTestcases==" + iCountTestcases + " paSs");
            return(true);
        }
        else
        {
            System.String strFailMsg = null;
            Console.WriteLine(strTest + strPath);
            Console.WriteLine(strTest + "FAiL");
            Console.Error.WriteLine(strTest + " iCountErrors==" + iCountErrors);
            return(false);
        }
    }
        public static void Write(FamicomDumperConnection dumper, string fileName, IEnumerable <int> badSectors, bool silent, bool needCheck = false, bool writePBBs = false)
        {
            byte[] PRG;
            if (Path.GetExtension(fileName).ToLower() == ".bin")
            {
                PRG = File.ReadAllBytes(fileName);
            }
            else
            {
                try
                {
                    var nesFile = new NesFile(fileName);
                    PRG = nesFile.PRG;
                }
                catch
                {
                    var nesFile = new UnifFile(fileName);
                    PRG = nesFile.Fields["PRG0"];
                }
            }

            int prgBanks = PRG.Length / 0x4000;

            Console.Write("Reset... ");
            dumper.Reset();
            Console.WriteLine("OK");
            var version    = DetectVersion(dumper);
            var coolboyReg = (ushort)(version == 2 ? 0x5000 : 0x6000);
            int flashSize  = CommonHelper.GetFlashSizePrintInfo(dumper);

            if (PRG.Length > flashSize)
            {
                throw new Exception("This ROM is too big for this cartridge");
            }
            PPBErase(dumper, coolboyReg);

            var writeStartTime = DateTime.Now;
            var lastSectorTime = DateTime.Now;
            var timeTotal      = new TimeSpan();
            int errorCount     = 0;

            for (int bank = 0; bank < prgBanks; bank++)
            {
                while (badSectors.Contains(bank / 8))
                {
                    bank += 8;                                   // bad sector :(
                }
                try
                {
                    byte r0 = (byte)(((bank >> 3) & 0x07)          // 5, 4, 3 bits
                                     | (((bank >> 9) & 0x03) << 4) // 10, 9 bits
                                     | (1 << 6));                  // resets 4th mask bit
                    byte r1 = (byte)((((bank >> 7) & 0x03) << 2)   // 8, 7
                                     | (((bank >> 6) & 1) << 4)    // 6
                                     | (1 << 7));                  // resets 5th mask bit
                    byte r2 = 0;
                    byte r3 = (byte)((1 << 4)                      // NROM mode
                                     | ((bank & 7) << 1));         // 2, 1, 0 bits
                    dumper.WriteCpu(coolboyReg, new byte[] { r0, r1, r2, r3 });

                    var data = new byte[0x4000];
                    int pos  = bank * 0x4000;
                    if (pos % (128 * 1024) == 0)
                    {
                        timeTotal      = new TimeSpan((DateTime.Now - lastSectorTime).Ticks * (prgBanks - bank) / 8);
                        timeTotal      = timeTotal.Add(DateTime.Now - writeStartTime);
                        lastSectorTime = DateTime.Now;
                        Console.Write("Erasing sector... ");
                        dumper.ErasePrgFlash(FamicomDumperConnection.FlashAccessType.Direct);
                        Console.WriteLine("OK");
                    }
                    Array.Copy(PRG, pos, data, 0, data.Length);
                    var timePassed = DateTime.Now - writeStartTime;
                    Console.Write("Writing {0}/{1} ({2}%, {3:D2}:{4:D2}:{5:D2}/{6:D2}:{7:D2}:{8:D2})... ", bank + 1, prgBanks, (int)(100 * bank / prgBanks),
                                  timePassed.Hours, timePassed.Minutes, timePassed.Seconds, timeTotal.Hours, timeTotal.Minutes, timeTotal.Seconds);
                    dumper.WritePrgFlash(0x0000, data, FamicomDumperConnection.FlashAccessType.Direct, false);
                    Console.WriteLine("OK");
                    if (writePBBs && ((bank % 8 == 7) || (bank == prgBanks - 1)))
                    {
                        PPBWrite(dumper, coolboyReg, (uint)bank / 8);
                    }
                }
                catch (Exception ex)
                {
                    errorCount++;
                    if (errorCount >= 3)
                    {
                        throw ex;
                    }
                    if (!silent)
                    {
                        Program.errorSound.PlaySync();
                    }
                    Console.WriteLine("Error: " + ex.Message);
                    bank = (bank & ~7) - 1;
                    Console.WriteLine("Lets try again");
                    Console.Write("Reset... ");
                    dumper.Reset();
                    Console.WriteLine("OK");
                    continue;
                }
            }
            if (errorCount > 0)
            {
                Console.WriteLine("Warning! Error count: {0}", errorCount);
            }

            if (needCheck)
            {
                Console.WriteLine("Starting check process");
                Console.Write("Reset... ");
                dumper.Reset();
                Console.WriteLine("OK");

                var readStartTime = DateTime.Now;
                lastSectorTime = DateTime.Now;
                timeTotal      = new TimeSpan();
                for (int bank = 0; bank < prgBanks; bank++)
                {
                    while (badSectors.Contains(bank / 8))
                    {
                        bank += 8;                                 // bad sector :(
                    }
                    byte r0 = (byte)(((bank >> 3) & 0x07)          // 5, 4, 3 bits
                                     | (((bank >> 9) & 0x03) << 4) // 10, 9 bits
                                     | (1 << 6));                  // resets 4th mask bit
                    byte r1 = (byte)((((bank >> 7) & 0x03) << 2)   // 8, 7
                                     | (((bank >> 6) & 1) << 4)    // 6
                                     | (1 << 7));                  // resets 5th mask bit
                    byte r2 = 0;
                    byte r3 = (byte)((1 << 4)                      // NROM mode
                                     | ((bank & 7) << 1));         // 2, 1, 0 bits
                    dumper.WriteCpu(coolboyReg, new byte[] { r0, r1, r2, r3 });

                    var data = new byte[0x4000];
                    int pos  = bank * 0x4000;
                    if (pos % (128 * 1024) == 0)
                    {
                        timeTotal      = new TimeSpan((DateTime.Now - lastSectorTime).Ticks * (prgBanks - bank) / 8);
                        timeTotal      = timeTotal.Add(DateTime.Now - readStartTime);
                        lastSectorTime = DateTime.Now;
                    }
                    Array.Copy(PRG, pos, data, 0, data.Length);
                    UInt16 crc = 0;
                    foreach (var a in data)
                    {
                        crc ^= a;
                        for (int i = 0; i < 8; ++i)
                        {
                            if ((crc & 1) != 0)
                            {
                                crc = (UInt16)((crc >> 1) ^ 0xA001);
                            }
                            else
                            {
                                crc = (UInt16)(crc >> 1);
                            }
                        }
                    }
                    var timePassed = DateTime.Now - readStartTime;
                    Console.Write("Reading CRC {0}/{1} ({2}%, {3:D2}:{4:D2}:{5:D2}/{6:D2}:{7:D2}:{8:D2})... ", bank + 1, prgBanks, (int)(100 * bank / prgBanks),
                                  timePassed.Hours, timePassed.Minutes, timePassed.Seconds, timeTotal.Hours, timeTotal.Minutes, timeTotal.Seconds);
                    var crcr = dumper.ReadCpuCrc(0x8000, 0x4000);
                    if (crcr != crc)
                    {
                        throw new Exception(string.Format("Check failed: {0:X4} != {1:X4}", crcr, crc));
                    }
                    else
                    {
                        Console.WriteLine("OK (CRC = {0:X4})", crcr);
                    }
                }
                if (errorCount > 0)
                {
                    Console.WriteLine("Warning! Error count: {0}", errorCount);
                    return;
                }
            }
        }
Пример #21
0
 /// <summary>
 /// Adds the specified number of days to the value of this instance.
 /// </summary>
 /// <param name="timeSpan">The time span.</param>
 /// <param name="value">A number of whole and fractional days. The <paramref name="value"/> parameter can be negative or positive.</param>
 /// <returns>
 /// A <see cref="T:System.TimeSpan"/> that represents the value of this instance plus the value of <paramref name="value"/>.
 /// </returns>
 /// <exception cref="T:System.OverflowException">The resulting <see cref="T:System.TimeSpan"/> is less than <see cref="F:System.TimeSpan.MinValue"/> or greater than <see cref="F:System.TimeSpan.MaxValue"/>.</exception>
 public static TimeSpan AddDays(this TimeSpan timeSpan, double value)
 {
     return(timeSpan.Add(TimeSpan.FromDays(value)));
 }
        public static void WriteWithGPIO(FamicomDumperConnection dumper, string fileName)
        {
            byte[] PRG;
            try
            {
                var nesFile = new NesFile(fileName);
                PRG = nesFile.PRG;
            }
            catch
            {
                var nesFile = new UnifFile(fileName);
                PRG = nesFile.Fields["PRG0"];
            }
            while (PRG.Length < 512 * 1024)
            {
                var PRGbig = new byte[PRG.Length * 2];
                Array.Copy(PRG, 0, PRGbig, 0, PRG.Length);
                Array.Copy(PRG, 0, PRGbig, PRG.Length, PRG.Length);
                PRG = PRGbig;
            }

            int prgBanks = PRG.Length / 0x2000;

            Console.Write("Reset... ");
            dumper.Reset();
            Console.WriteLine("OK");
            var version    = DetectVersion(dumper);
            var CoolboyReg = (UInt16)(version == 2 ? 0x5000 : 0x6000);

            dumper.WriteCpu(0xA001, 0x00); // RAM protect
            var writeStartTime = DateTime.Now;
            var lastSectorTime = DateTime.Now;
            var timeTotal      = new TimeSpan();

            for (int bank = 0; bank < prgBanks; bank += 2)
            {
                int  outbank = bank / 16;
                byte r0      = (byte)((outbank & 0x07) | ((outbank & 0xc0) >> 2));
                byte r1      = (byte)(((outbank & 0x30) >> 2) | ((outbank << 1) & 0x10));
                byte r2      = 0;
                byte r3      = 0;
                dumper.WriteCpu(CoolboyReg, new byte[] { r0, r1, r2, r3 });

                int inbank = bank % 64;
                dumper.WriteCpu(0x8000, new byte[] { 6, (byte)(inbank) });
                dumper.WriteCpu(0x8000, new byte[] { 7, (byte)(inbank | 1) });

                var data = new byte[0x4000];
                int pos  = bank * 0x2000;
                if (pos % (128 * 1024) == 0)
                {
                    timeTotal      = new TimeSpan((DateTime.Now - lastSectorTime).Ticks * (prgBanks - bank) / 16);
                    timeTotal      = timeTotal.Add(DateTime.Now - writeStartTime);
                    lastSectorTime = DateTime.Now;
                    Console.Write("Erasing sector... ");
                    dumper.ErasePrgFlash(FamicomDumperConnection.FlashAccessType.CoolboyGPIO);
                    Console.WriteLine("OK");
                }
                Array.Copy(PRG, pos, data, 0, data.Length);
                var timePassed = DateTime.Now - writeStartTime;
                Console.Write("Writing {0}/{1} ({2}%, {3:D2}:{4:D2}:{5:D2}/{6:D2}:{7:D2}:{8:D2})... ", bank / 2 + 1, prgBanks / 2, (int)(100 * bank / prgBanks),
                              timePassed.Hours, timePassed.Minutes, timePassed.Seconds, timeTotal.Hours, timeTotal.Minutes, timeTotal.Seconds);
                dumper.WritePrgFlash(0x0000, data, FamicomDumperConnection.FlashAccessType.CoolboyGPIO, false);
                Console.WriteLine("OK");
            }
        }
Пример #23
0
        public int UpdateMedias(ManagedSecurityContext sec)
        {
            GetACL().Check(sec, DataOperation.Update);

            int result   = 0;
            Uri basehref = null;

            Uri.TryCreate(mInstance.LinkUrl, UriKind.Absolute, out basehref);

            IList items = Session.CreateCriteria(typeof(AccountFeedItem))
                          .Add(Expression.Eq("AccountFeed.Id", mInstance.Id))
                          .List();

            TimeSpan tsDistribution = new TimeSpan(0, 30, 0);

            foreach (AccountFeedItem item in items)
            {
                List <HtmlGenericControl> embed = HtmlObjectExtractor.Extract(item.Description, basehref);
                foreach (HtmlGenericControl control in embed)
                {
                    string content = HtmlGenericCollector.GetHtml(control);

                    AccountFeedItemMedia x_media = null;

                    // media may appear only once, repeating media don't get updated
                    // TODO: expensive LIKE query

                    x_media = Session.CreateCriteria(typeof(AccountFeedItemMedia))
                              .Add(Expression.Like("EmbeddedHtml", content))
                              .UniqueResult <AccountFeedItemMedia>();

                    if (x_media != null)
                    {
                        continue;
                    }

                    try
                    {
                        x_media = new AccountFeedItemMedia();
                        x_media.AccountFeedItem = item;
                        x_media.Created         = item.Created.Subtract(tsDistribution); // shuffle images
                        tsDistribution          = tsDistribution.Add(new TimeSpan(0, 30, 0));
                        x_media.Modified        = DateTime.UtcNow;
                        x_media.EmbeddedHtml    = content;
                        x_media.Type            = HtmlObjectExtractor.GetType(control);
                        x_media.Visible         = mInstance.PublishMedia;
                        x_media.Interesting     = false;
                    }
                    catch (Exception ex)
                    {
                        x_media.LastError = ex.Message;
                        x_media.Visible   = false;
                    }

                    if (string.IsNullOrEmpty(x_media.Type))
                    {
                        continue;
                    }

                    Session.Save(x_media);
                    result++;
                }
            }

            return(result);
        }
        /// <summary>
        ///     Called when the location has changed.
        /// </summary>
        /// <param name="location">The new location, as a Location object.</param>
        /// <since version="Added in API level 1" />
        /// <remarks>
        ///     <para tool="javadoc-to-mdoc">
        ///         Called when the location has changed.
        ///     </para>
        ///     <para tool="javadoc-to-mdoc"> There are no restrictions on the use of the supplied Location object.</para>
        ///     <para tool="javadoc-to-mdoc">
        ///         <format type="text/html">
        ///             <a
        ///                 href="http://developer.android.com/reference/android/location/LocationListener.html#onLocationChanged(android.location.Location)"
        ///                 target="_blank">
        ///                 [Android Documentation]
        ///             </a>
        ///         </format>
        ///     </para>
        /// </remarks>
        public void OnLocationChanged(Location location)
        {
            if (location.Provider != _activeProvider)
            {
                if (_activeProvider != null && _manager.IsProviderEnabled(_activeProvider))
                {
                    var pr     = _manager.GetProvider(location.Provider);
                    var lapsed = GetTimeSpan(location.Time) - GetTimeSpan(_lastLocation.Time);

                    if (pr.Accuracy > _manager.GetProvider(_activeProvider).Accuracy&& lapsed < _timePeriod.Add(_timePeriod))
                    {
                        location.Dispose();
                        return;
                    }
                }

                _activeProvider = location.Provider;
            }

            var previous = Interlocked.Exchange(ref _lastLocation, location);

            if (previous != null)
            {
                previous.Dispose();
            }

            var p = new Position();

            if (location.HasAccuracy)
            {
                p.Accuracy = location.Accuracy;
            }
            if (location.HasAltitude)
            {
                p.Altitude = location.Altitude;
            }
            if (location.HasBearing)
            {
                p.Heading = location.Bearing;
            }
            if (location.HasSpeed)
            {
                p.Speed = location.Speed;
            }

            p.Longitude = location.Longitude;
            p.Latitude  = location.Latitude;
            p.Timestamp = Geolocator.GetTimestamp(location);

            var changed = PositionChanged;

            if (changed != null)
            {
                changed(this, new PositionEventArgs(p));
            }
        }
Пример #25
0
        /// <summary>
        /// Starts the ignite with three policies (two in-memory and one persistent).
        /// </summary>
        private static IIgnite StartIgniteWithThreeDataRegions()
        {
            var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
            {
                DataStorageConfiguration = new DataStorageConfiguration()
                {
                    CheckpointFrequency            = CheckpointFrequency,
                    MetricsEnabled                 = true,
                    WalMode                        = WalMode.LogOnly,
                    DefaultDataRegionConfiguration = new DataRegionConfiguration
                    {
                        Name = RegionWithMetrics,
                        PersistenceEnabled = false,
                        MetricsEnabled     = true
                    },
                    DataRegionConfigurations = new[]
                    {
                        new DataRegionConfiguration
                        {
                            Name           = RegionNoMetrics,
                            MetricsEnabled = false
                        },
                        new DataRegionConfiguration()
                        {
                            Name = RegionWithMetricsAndPersistence,
                            PersistenceEnabled = true,
                            MetricsEnabled     = true
                        }
                    }
                },
                WorkDirectory = TempDir
            };

            var ignite = Ignition.Start(cfg);

            ignite.GetCluster().SetActive(true);

            // Create caches and do some things with them.
            var cacheNoMetrics = ignite.CreateCache <int, int>(new CacheConfiguration("cacheNoMetrics")
            {
                DataRegionName = RegionNoMetrics
            });

            cacheNoMetrics.Put(1, 1);
            cacheNoMetrics.Get(1);

            var cacheWithMetrics = ignite.CreateCache <int, int>(new CacheConfiguration("cacheWithMetrics")
            {
                DataRegionName = RegionWithMetrics
            });

            cacheWithMetrics.Put(1, 1);
            cacheWithMetrics.Get(1);

            var cacheWithMetricsAndPersistence =
                ignite.CreateCache <int, int>(new CacheConfiguration("cacheWithMetricsAndPersistence")
            {
                DataRegionName = RegionWithMetricsAndPersistence
            });

            cacheWithMetricsAndPersistence.Put(1, 1);
            cacheWithMetricsAndPersistence.Get(1);

            // Wait for checkpoint. Wait for two times than CheckpointFrequency.
            Thread.Sleep(CheckpointFrequency.Add(CheckpointFrequency));

            return(ignite);
        }
Пример #26
0
        static void Main()
        {
            Console.WriteLine(@"Создайте папку D:\\Pictures, сохраните в ней тестовое изображение. 
В этой же папке будут сохранены изображения, соответствующие множествам уровня");
            Console.WriteLine("\nВведите имя файла, например, 1.jpg");
            Console.WriteLine(@"Если вы хотите использовать другой путь, введите его целиком в формате
C:\test\image1.jpg");
            Console.WriteLine();
            string input = Console.ReadLine();

            if (input.Contains(":"))
            {
                imagePath = Path.GetDirectoryName(input);
            }
            string path = Path.Combine(imagePath, input);

            Console.WriteLine("Введите номер желаемого алгоритма обработки изображения:");
            Console.WriteLine("1) монохромное изображение");
            Console.WriteLine("2) красная компонента RGB");
            Console.WriteLine("3) зелёная компонента RGB");
            Console.WriteLine("4) синяя компонента RGB");
            Console.WriteLine("5) компонента Hue палитры HSV");
            Console.WriteLine();

            int converterNumber;

            int.TryParse(Console.ReadLine(), out converterNumber);
            ConverterType converterType = (ConverterType)(converterNumber - 1);

            int directoryNumber = GetDirectoryNumber(imagePath);

            LayersDirectoryPath = Path.Combine(imagePath, "Layers ") + directoryNumber.ToString();
            Directory.CreateDirectory(LayersDirectoryPath);

            var spectrumBuilder = new SpectrumBuilder();
            var layersBuilder   = new LayersBuilder();

            //Вычисление показателей сингулярности
            DateTime before = DateTime.Now;

            var image_before = (Bitmap)Image.FromFile(path);
            var image        = ImageConverter.ConvertBitmap(image_before, converterType);

            Console.WriteLine("\nВычисляются показатели сингулярности...");
            var singularityBounds = layersBuilder.GetSingularityBounds(image, converterType);

            DateTime after       = DateTime.Now;
            TimeSpan firstPeriod = after - before;

            Console.WriteLine($"Время вычисления показателей {firstPeriod.ToString()}");


            Console.WriteLine("Minimal singularity:   {0:0.00}", singularityBounds.Begin);
            Console.WriteLine("Maximal singularity:   {0:0.00}", singularityBounds.End);

            Console.WriteLine("\nВведите шаг между уровнями, например, 0,2");
            double singulatityStep = double.Parse(Console.ReadLine());

            //Вычисление множеств уровня
            Console.WriteLine("\nВычисляются множества уровня...");
            before = DateTime.Now;
            var layers = layersBuilder.SplitByLayers(singularityBounds, singulatityStep);

            after = DateTime.Now;
            TimeSpan secondPeriod = after - before;

            Console.WriteLine($"Время определения уровней {secondPeriod.ToString()}");

            //Вычисление спектра
            Console.WriteLine("\nВычисляется мультифрактальный спектр...");
            before = DateTime.Now;
            var spectrum = spectrumBuilder.CalculateSpectrum(image, layers, singularityBounds, singulatityStep);

            after = DateTime.Now;
            TimeSpan thirdPeriod = after - before;

            Console.WriteLine($"Время вычисления спектра {thirdPeriod.ToString()}");

            Console.WriteLine("\nМножества уровня построены");
            Console.WriteLine("Номер папки с множествами уровня : {0}", directoryNumber);
            Console.WriteLine("Мультифрактальный спектр вычислен и находится в файле spectrum.txt");

            //Сохранение спектра в текстовый файл
            string actualSpectrumPath = Path.Combine(LayersDirectoryPath, spectrumFileName);

            using (StreamWriter sw = new StreamWriter(actualSpectrumPath, true))
            {
                sw.WriteLine("*********************");
                var outputInfo = new StringBuilder();
                foreach (var layerInfo in spectrum)
                {
                    outputInfo.Append(string.Format("{0:0.00 }", layerInfo.Key));
                    outputInfo.Append(string.Format("{0:0.00}\r\n", layerInfo.Value));
                }
                sw.WriteLine(outputInfo);
                sw.Close();
            }

            Console.WriteLine($"Общее время работы программы {firstPeriod.Add(secondPeriod).Add(thirdPeriod).ToString()}");

            Console.WriteLine("\nЖелаем вам всего доброго!");
            Console.ReadKey();
        }
Пример #27
0
        private void OnTick(object args, System.Timers.ElapsedEventArgs e)
        {
            measureCount++;

            if (rests == true)
            {
                if (rightHand == 0)
                {
                    if (!tickingRight)
                    {
                        tickingRight = true;
                    }
                    else
                    {
                        // Only displays quarter rests
                        rightRest = rightRest.Add(new TimeSpan(noteEstimator.SixteenthCount));
                        if (rightRest.Ticks >= (int)noteEstimator.QuartCount)
                        {
                            offset += 45;
                            sheetForm.ScrollWidth += 45;
                            sheetForm.StaffWidth  += 45;
                            sheetForm.Rests.Add(new Symbol("\uD834\uDD3D", 60, offset, 150));
                            rightRest = rightRest.Subtract(new TimeSpan(noteEstimator.QuartCount));
                        }
                    }
                }
                if (rightHand != 0 && tickingRight)
                {
                    tickingRight = false;
                }

                if (leftHand == 0)
                {
                    if (!tickingLeft)
                    {
                        tickingLeft = true;
                    }
                    else
                    {
                        // Only displays quarter rests
                        leftRest = leftRest.Add(new TimeSpan(noteEstimator.SixteenthCount));

                        if (leftRest.Ticks >= (int)noteEstimator.QuartCount)
                        {
                            offset += 45;
                            sheetForm.ScrollWidth += 45;
                            sheetForm.StaffWidth  += 45;
                            sheetForm.Rests.Add(new Symbol("\uD834\uDD3D", 60, offset, 300));
                            leftRest = leftRest.Subtract(new TimeSpan(noteEstimator.QuartCount));
                        }
                    }
                }
                if (leftHand != 0 && tickingLeft)
                {
                    tickingLeft = false;
                }
            }
            if (measureCount > 16)
            {
                sheetForm.MeasurePositions.Add(measure.Width);
                measure.Width += 900;
                measureCount   = 0;
            }
        }
Пример #28
0
        /// <summary>
        /// Download the data using HttpWebRequest. It will read a buffer of bytes from the
        /// response stream, and store the buffer to a MemoryStream cache first.
        /// If the cache is full, or the download is paused, canceled or completed, write
        /// the data in cache to local file.
        /// </summary>
        void DownloadInternal(object obj)
        {
            if (this.Status != DownloadStatus.Waiting)
            {
                return;
            }

            HttpWebRequest  webRequest     = null;
            HttpWebResponse webResponse    = null;
            Stream          responseStream = null;
            MemoryStream    downloadCache  = null;

            this.lastStartTime = DateTime.Now;

            try
            {
                if (!HasChecked)
                {
                    string filename = string.Empty;
                    CheckUrlAndFile();
                }

                this.EnsurePropertyValid();

                // Set the status.
                this.Status = DownloadStatus.Downloading;

                // Create a request to the file to be  downloaded.
                webRequest = DownloaderHelper.InitializeHttpWebRequest(this);

                // Specify the block to download.
                if (EndPoint != int.MaxValue)
                {
                    webRequest.AddRange((int)(StartPoint + DownloadedSize), (int)EndPoint);
                }
                else
                {
                    webRequest.AddRange((int)(StartPoint + DownloadedSize));
                }

                // Retrieve the response from the server and get the response stream.
                webResponse = (HttpWebResponse)webRequest.GetResponse();

                responseStream = webResponse.GetResponseStream();


                // Cache data in memory.
                downloadCache = new MemoryStream(this.MaxCacheSize);

                byte[] downloadBuffer = new byte[this.BufferSize];

                int bytesSize = 0;
                CachedSize = 0;
                int receivedBufferCount = 0;

                // Download the file until the download is paused, canceled or completed.
                while (true)
                {
                    // Read a buffer of data from the stream.
                    bytesSize = responseStream.Read(downloadBuffer, 0, downloadBuffer.Length);

                    // If the cache is full, or the download is paused, canceled or
                    // completed, write the data in cache to local file.
                    if (this.Status != DownloadStatus.Downloading ||
                        bytesSize == 0 ||
                        this.MaxCacheSize < CachedSize + bytesSize)
                    {
                        try
                        {
                            // Write the data in cache to local file.
                            WriteCacheToFile(downloadCache, CachedSize);

                            this.DownloadedSize += CachedSize;

                            // Stop downloading the file if the download is paused,
                            // canceled or completed.
                            if (this.Status != DownloadStatus.Downloading ||
                                bytesSize == 0)
                            {
                                break;
                            }

                            // Reset cache.
                            downloadCache.Seek(0, SeekOrigin.Begin);
                            CachedSize = 0;
                        }
                        catch (Exception ex)
                        {
                            string strError = ex.ToString();
                            ErrorCollection.GetInstance().SetErrorInfo(strError);

                            // Fire the DownloadCompleted event with the error.
                            this.OnDownloadCompleted(
                                new DownloadCompletedEventArgs(
                                    null,
                                    this.DownloadedSize,
                                    this.TotalSize,
                                    this.TotalUsedTime,
                                    ex));
                            return;
                        }
                    }

                    // Write the data from the buffer to the cache in memory.
                    downloadCache.Write(downloadBuffer, 0, bytesSize);

                    CachedSize += bytesSize;

                    receivedBufferCount++;

                    // Fire the DownloadProgressChanged event.
                    if (receivedBufferCount == this.BufferCountPerNotification)
                    {
                        InternalDownloadProgressChanged(CachedSize);
                        receivedBufferCount = 0;
                    }
                }


                // Update the used time when the current doanload is stopped.
                usedTime = usedTime.Add(DateTime.Now - lastStartTime);

                // Update the status of the client. Above loop will be stopped when the
                // status of the client is pausing, canceling or completed.
                if (this.Status == DownloadStatus.Pausing)
                {
                    this.Status = DownloadStatus.Paused;
                }
                else if (this.Status == DownloadStatus.Canceling)
                {
                    this.Status = DownloadStatus.Canceled;
                }
                else
                {
                    this.Status = DownloadStatus.Completed;
                    return;
                }
            }
            catch (Exception ex)
            {
                string strError = ex.ToString();
                ErrorCollection.GetInstance().SetErrorInfo(strError);

                // Fire the DownloadCompleted event with the error.
                this.OnDownloadCompleted(
                    new DownloadCompletedEventArgs(
                        null,
                        this.DownloadedSize,
                        this.TotalSize,
                        this.TotalUsedTime,
                        ex));
                return;
            }
            finally
            {
                // When the above code has ended, close the streams.
                if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (webResponse != null)
                {
                    webResponse.Close();
                }
                if (downloadCache != null)
                {
                    downloadCache.Close();
                }
            }
        }
Пример #29
0
        static void Main(string[] args)
        {
            var db3 = new DBEntityInfomation();
            db3.Property.Speed = 1;
            db3.Property.Position.X = 4530;
            db3.Property.Position.Y = 5430;

            var db4 = new DBEntityInfomation();
            db4.Property.Position.X = 100;
            db4.Property.Position.Y = 33220;

            System.TimeSpan time = new TimeSpan(0, 0, 0);
            PlayerMoverAbility pma = new PlayerMoverAbility(db3);
            pma.Move(db4.Property.Position, time.Ticks);

            pma.Update(time.Add(new TimeSpan(0,0,50)).Ticks);

            pma.Update(time.Add(new TimeSpan(0, 0, 99)).Ticks);

            DBEntityInfomation db1 = new DBEntityInfomation();
            db1.Property.Position.X = 100;
            DBEntityInfomation db2 = new DBEntityInfomation();
            db2.Property.Position.X = 100;
            db2.Look.Name = "dff";
            var ret = Regulus.Utility.ValueHelper.DeepEqual(db1, db2);
            Regulus.NoSQL.Database db = new Regulus.NoSQL.Database();
            db.Launch("mongodb://127.0.0.1:27017", "Keys");
            db.Shutdown();
        }
Пример #30
0
    // testa qual a euristica mais rápida entre heuristics1 e heuristicsA
    static public void testPerformnace1(int numOfBorads)
    {
        Pentago_GameBoard[] testBoardsWhites = new Pentago_GameBoard[numOfBorads];
        Pentago_GameBoard[] testBoardsBlacks = new Pentago_GameBoard[numOfBorads];

        for (int i = 0; i < numOfBorads; i++)
        {
            int numPieces = GenerateRandomBoard.GetRandomNumber(0, 17);
            Console.WriteLine("Num of pieces " + numPieces);
            GenerateRandomBoard rndBoard;

            Console.WriteLine("white");

            rndBoard = new GenerateRandomBoard(numPieces == 0? 0: numPieces - 1, true); // -1 prencipio de iguldade de peças do tabuleiro
            rndBoard.generateNewBoard();
            testBoardsWhites[i] = rndBoard.Pentago_gb;
            testBoardsWhites[i].print_board();

            Console.WriteLine("black");

            rndBoard = new GenerateRandomBoard(numPieces, false);
            rndBoard.generateNewBoard();
            testBoardsBlacks[i] = rndBoard.Pentago_gb;
            testBoardsBlacks[i].print_board();
        }

        // heuristics1
        Pentago_Rules wrules1 = new Pentago_Rules(Pentago_Rules.EvaluationFunction.heuristic1,
                                                  Pentago_Rules.NextStatesFunction.all_states,
                                                  Pentago_Rules.IA_PIECES_WHITES, false);
        MINMAX        test_w1 = new MINMAX(MINMAX.VERSION.minmax, wrules1, 4);
        Pentago_Rules brules1 = new Pentago_Rules(Pentago_Rules.EvaluationFunction.heuristic1,
                                                  Pentago_Rules.NextStatesFunction.all_states,
                                                  Pentago_Rules.IA_PIECES_BLACKS, false);
        MINMAX test_b1 = new MINMAX(MINMAX.VERSION.minmax, brules1, 4);

        // heuristicsA
        Pentago_Rules wrulesA = new Pentago_Rules(Pentago_Rules.EvaluationFunction.heuristicA,
                                                  Pentago_Rules.NextStatesFunction.all_states,
                                                  Pentago_Rules.IA_PIECES_WHITES, false);
        MINMAX        test_wA = new MINMAX(MINMAX.VERSION.minmax, wrulesA, 4);
        Pentago_Rules brulesA = new Pentago_Rules(Pentago_Rules.EvaluationFunction.heuristicA,
                                                  Pentago_Rules.NextStatesFunction.all_states,
                                                  Pentago_Rules.IA_PIECES_BLACKS, false);
        MINMAX test_bA = new MINMAX(MINMAX.VERSION.minmax, brulesA, 4);



        TimeSpan test1_1 = Performance.PerformanceTimes(test_w1, testBoardsWhites);
        TimeSpan test2_1 = Performance.PerformanceTimes(test_b1, testBoardsBlacks);

        TimeSpan ts_1 = test1_1.Add(test2_1);

        // Format and display the TimeSpan value.
        string elapsedTime_1 = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                             ts_1.Hours, ts_1.Minutes, ts_1.Seconds,
                                             ts_1.Milliseconds / 10);

        Console.WriteLine("RunTime heuristic1 " + elapsedTime_1);
        //////////////////////////////////////////////////////////////////////////////
        TimeSpan test1_A = Performance.PerformanceTimes(test_wA, testBoardsWhites);
        TimeSpan test2_A = Performance.PerformanceTimes(test_bA, testBoardsBlacks);

        TimeSpan ts_A = test1_A.Add(test2_A);

        // Format and display the TimeSpan value.
        string elapsedTime_A = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                             ts_A.Hours, ts_A.Minutes, ts_A.Seconds,
                                             ts_A.Milliseconds / 10);

        Console.WriteLine("RunTime heuristicA " + elapsedTime_A);
    }
Пример #31
0
        /// <summary>
        ///     Converts time literal value.
        /// </summary>
        private static TimeSpan ConvertTimeLiteralValue(string datetimeLiteralValue)
        {
            var datetimeParts = datetimeLiteralValue.Split(_datetimeSeparators, StringSplitOptions.RemoveEmptyEntries);

            Debug.Assert(datetimeParts.Length >= 2, "time literal value must have at least 2 parts");

            int hour;
            int minute;
            int second;
            int ticks;
            GetTimeParts(datetimeLiteralValue, datetimeParts, 0, out hour, out minute, out second, out ticks);

            Debug.Assert(hour >= 0 && hour <= 24);
            Debug.Assert(minute >= 0 && minute <= 59);
            Debug.Assert(second >= 0 && second <= 59);
            Debug.Assert(ticks >= 0 && ticks <= 9999999);
            var ts = new TimeSpan(hour, minute, second);
            ts = ts.Add(new TimeSpan(ticks));
            return ts;
        }
Пример #32
0
 private static object Add(TimeSpan first, Int32 second)
 {
     return(first.Add(TimeSpan.FromHours(second)));
 }