示例#1
0
 def test_save(self):
     
     create_class(ClassToSave, client=self.client)
     
     class_to_save = ClassToSave()
     class_to_save.int_field = 10
     class_to_save.str_field = 'foobar'
     class_to_save.datetime_field = Arrow.utcnow()
     class_to_save.float_field = 12345.547
     class_to_save.save(client=self.client)
     loaded_class = ClassToSave.get(class_to_save.rid, client=self.client)
     self.assertEqual(class_to_save.__class__, loaded_class.__class__)
     self.assertEqual(loaded_class.rid, class_to_save.rid)
     self.assertEqual(loaded_class.str_field, class_to_save.str_field)
     self.assertEqual(loaded_class.int_field, class_to_save.int_field)
     self.assertEqual(loaded_class.datetime_field, class_to_save.datetime_field)
     self.assertEqual(loaded_class.float_field, class_to_save.float_field)
     self.assertEqual(loaded_class.bool_field, class_to_save.bool_field)
     class_to_save.int_field = 20
     class_to_save.str_field = 'foobarioioioioio'
     class_to_save.datetime_field = Arrow.utcnow()
     class_to_save.float_field = None
     class_to_save.bool_field = False
     class_to_save.save(client=self.client)
     loaded_class = ClassToSave.get(class_to_save.rid, client=self.client)
     self.assertEqual(class_to_save.__class__, loaded_class.__class__)
     self.assertEqual(loaded_class.rid, class_to_save.rid)
     self.assertEqual(loaded_class.str_field, class_to_save.str_field)
     self.assertEqual(loaded_class.int_field, class_to_save.int_field)
     self.assertEqual(loaded_class.datetime_field, class_to_save.datetime_field)
     self.assertEqual(loaded_class.float_field, class_to_save.float_field)
     self.assertEqual(loaded_class.bool_field, class_to_save.bool_field)
示例#2
0
文件: calender.py 项目: VinoxM/yobot
 def get_day_events(self, match_num) -> tuple:
     if match_num == 2 or match_num == 12 or match_num == 22 or match_num == 32:
         daystr = "今天"
         date = Arrow.now(tzinfo=self.timezone)
     elif match_num == 3 or match_num == 13 or match_num == 23 or match_num == 33:
         daystr = "明天"
         date = Arrow.now(tzinfo=self.timezone) + datetime.timedelta(days=1)
     elif match_num & 0xf00000 == 0x100000:
         year = (match_num & 0xff000) >> 12
         month = (match_num & 0xf00) >> 8
         day = match_num & 0xff
         daystr = "{}年{}月{}日".format(2000 + year, month, day)
         try:
             date = Arrow(2000 + year, month, day)
         except ValueError as v:
             raise InputError("日期错误:{}".format(v))
     if match_num - 30 > 0:
         daystr = "日服" + daystr
         events = self.timeline_jp.at(date)
     elif match_num - 20 > 0:
         daystr = "台服" + daystr
         events = self.timeline_tw.at(date)
     elif match_num - 10 > 0:
         daystr = "国服" + daystr
         events = self.timeline_cn.at(date)
     else:
         daystr = self.region[self.setting.get("calender_region",
                                               "default")] + daystr
         events = self.timeline.at(date)
     return (daystr, events)
示例#3
0
    def get_day_events(self, match_num, region) -> tuple:
        if match_num == 2:
            daystr = "今天"
            date = Arrow.now(tzinfo=self.timezone)
        elif match_num == 3:
            daystr = "明天"
            date = Arrow.now(tzinfo=self.timezone) + datetime.timedelta(days=1)
        elif match_num & 0xf00000 == 0x100000:
            year = (match_num & 0xff000) >> 12
            month = (match_num & 0xf00) >> 8
            day = match_num & 0xff
            daystr = "{}年{}月{}日".format(2000 + year, month, day)
            try:
                date = Arrow(2000 + year, month, day)
            except ValueError as v:
                raise InputError("日期错误:{}".format(v))

        timeline = self.timeline_cn
        if region == "jp":
            timeline = self.timeline_jp
        elif region == "tw":
            timeline = self.timeline_tw
        if not timeline:
            events = None
        else:
            events = timeline.at(date)

        return (daystr, events)
    def test_create_no_holidays(self):
        """test create appointment, no holiday to avoid after 1900"""
        import_holidays()
        appt_datetime = Arrow.fromdatetime(datetime(1900, 1, 1)).datetime
        expected_appt_datetime = Arrow.fromdatetime(datetime(1900, 1,
                                                             2)).datetime
        creator = AppointmentCreator(
            subject_identifier=self.subject_identifier,
            visit_schedule_name=self.visit_schedule.name,
            schedule_name=self.schedule.name,
            visit=self.visit1000,
            timepoint_datetime=appt_datetime,
        )
        self.assertEqual(Appointment.objects.all()[0], creator.appointment)
        self.assertEqual(Appointment.objects.all()[0].appt_datetime,
                         expected_appt_datetime)

        appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
        creator = AppointmentCreator(
            subject_identifier=self.subject_identifier,
            visit_schedule_name=self.visit_schedule.name,
            schedule_name=self.schedule.name,
            visit=self.visit1000,
            timepoint_datetime=appt_datetime,
        )
        self.assertEqual(Appointment.objects.all()[0], creator.appointment)
        self.assertEqual(Appointment.objects.all()[0].appt_datetime,
                         appt_datetime)
示例#5
0
def year_range(date):

    start_date = datetime.datetime(date.year, 1, 1)
    end_date = datetime.datetime(date.year, 12, 31)

    start_date = Arrow.fromdatetime(start_date)
    end_date = Arrow.fromdatetime(end_date)

    return (start_date, end_date)
示例#6
0
 def test_available_arw_with_holiday(self):
     """Asserts finds available_arw on first clinic day after holiday."""
     suggested_date = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
     expected_date = Arrow.fromdatetime(datetime(2017, 1, 8)).datetime
     facility = Facility(name="clinic",
                         days=[suggested_date.weekday()],
                         slots=[100])
     available_arw = facility.available_arw(suggested_date)
     self.assertEqual(expected_date, available_arw.datetime)
示例#7
0
def month_range(date):

    # https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python/27667421#27667421
    start_date = datetime.datetime(date.year, date.month, 1)
    end_date = start_date + relativedelta(months=1, days=-1)

    start_date = Arrow.fromdatetime(start_date)
    end_date = Arrow.fromdatetime(end_date)

    return (start_date, end_date)
示例#8
0
 def test_read_holidays_from_db(self):
     """Asserts finds available_arw on first clinic day after holiday."""
     suggested_date = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
     expected_date = Arrow.fromdatetime(datetime(2017, 1, 8)).datetime
     Holiday.objects.create(local_date=suggested_date)
     facility = Facility(name="clinic",
                         days=[suggested_date.weekday()],
                         slots=[100])
     available_arw = facility.available_arw(suggested_date)
     self.assertEqual(expected_date, available_arw.datetime)
 def test_create(self):
     appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
     creator = AppointmentCreator(
         subject_identifier=self.subject_identifier,
         visit_schedule_name=self.visit_schedule.name,
         schedule_name=self.schedule.name,
         visit=self.visit1000,
         timepoint_datetime=appt_datetime)
     appointment = creator.appointment
     self.assertEqual(
         Appointment.objects.all()[0], appointment)
     self.assertEqual(
         Appointment.objects.all()[0].appt_datetime,
         Arrow.fromdatetime(datetime(2017, 1, 3)).datetime)
示例#10
0
文件: calender.py 项目: VinoxM/yobot
 def get_week_events(self, match_num) -> str:
     reply = "一周日程:"
     preffix = ""
     date = Arrow.now(tzinfo=self.timezone)
     for (k, i) in enumerate(range(7)):
         if match_num - 10 == 4:
             if k == 0: preffix += "国服"
             events = self.timeline_cn.at(date)
         elif match_num - 20 == 4:
             if k == 0: preffix += "台服"
             events = self.timeline_tw.at(date)
         elif match_num - 30 == 4:
             if k == 0: preffix += "日服"
             events = self.timeline_jp.at(date)
         else:
             if k == 0:
                 preffix += self.region[self.setting.get(
                     "calender_region", "default")]
             events = self.timeline.at(date)
         events_str = "\n⨠".join(events)
         if events_str == "":
             events_str = "没有记录"
         daystr = date.format("MM月DD日")
         reply += "\n======{}======\n⨠{}".format(daystr, events_str)
         date += datetime.timedelta(days=1)
     reply += "\n\n更多日程:{}".format(
         _calender_url.get(self.setting["calender_region"]))
     return preffix + reply
示例#11
0
    def formatTime(self, record, datefmt=None):
        arrow_time = Arrow.fromtimestamp(record.created)

        if datefmt:
            arrow_time = arrow_time.format(datefmt)

        return str(arrow_time)
 def test_create_appt_moves_forward(self):
     """Assert appt datetime moves forward to avoid holidays"""
     appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
     creator = AppointmentCreator(
         subject_identifier=self.subject_identifier,
         visit_schedule_name=self.visit_schedule.name,
         schedule_name=self.schedule.name,
         visit=self.visit1000,
         timepoint_datetime=appt_datetime,
     )
     appointment = creator.appointment
     self.assertEqual(Appointment.objects.all()[0], appointment)
     self.assertEqual(
         Appointment.objects.all()[0].appt_datetime,
         Arrow.fromdatetime(datetime(2017, 1, 3)).datetime,
     )
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.longitudinal_refset.order_by('hiv_result_datetime')
        elisa_hiv_result = None
        elisa_hiv_result_datetime = None
        # try to get the first POS
        for index, result in enumerate(
                self.longitudinal_refset.fieldset('hiv_result')):
            if result == POS:
                elisa_hiv_result = result
                elisa_hiv_result_datetime = self.longitudinal_refset.fieldset(
                    'hiv_result_datetime')[index]
                break
        # if not, get the most recent result (last)
        if not elisa_hiv_result:
            elisa_hiv_result = self.longitudinal_refset.fieldset(
                'hiv_result').last()
            elisa_hiv_result_datetime = self.longitudinal_refset.fieldset(
                'hiv_result_datetime').last()

        self.values.update(elisa_hiv_result=elisa_hiv_result)
        if elisa_hiv_result_datetime:
            self.values.update(elisa_hiv_result_date=Arrow.fromdatetime(
                elisa_hiv_result_datetime).date())
        else:
            self.values.update(elisa_hiv_result_date=None)
        self.values.update(hiv_result=elisa_hiv_result)
        self.values.update(hiv_result_datetime=elisa_hiv_result_datetime)
        self.values.update(elisa_hiv_result=elisa_hiv_result)
        self.values.update(elisa_hiv_result_datetime=elisa_hiv_result_datetime)
示例#14
0
 def test_type_validation(self):
     
     field = DateTimeField()
     field.value = 'f'
     self.assertRaises(ValidationError, field._type_validation)
     field.value = Arrow.utcnow()
     field._type_validation()
示例#15
0
 def label_context(self):
     tz = pytz.timezone(settings.TIME_ZONE)
     local = Arrow.fromdatetime(self.requisition.drawn_datetime
                                or self.requisition.created).to(tz)
     formatted_date = local.format("YYYY-MM-DD HH:mm")
     printed = "PRINTED: " if not self.requisition.drawn_datetime else "DRAWN: "
     drawn_datetime = f"{printed}{formatted_date}"
     try:
         clinician_initials = self.requisition.user_created[0:2].upper()
     except IndexError:
         clinician_initials = "??"
     return {
         "requisition_identifier": self.requisition.requisition_identifier,
         "item": self.item,
         "item_count": self.requisition.item_count or 1,
         "primary": "<P>",
         "barcode_value": self.requisition.requisition_identifier,
         "protocol": Protocol().protocol,
         "site": str(self.requisition.site.id),
         "site_name": str(self.requisition.site.name),
         "site_title": str(self.requisition.site.siteprofile.title),
         "clinician_initials": clinician_initials,
         "drawn_datetime": drawn_datetime,
         "subject_identifier": self.registered_subject.subject_identifier,
         "gender": self.registered_subject.gender,
         "dob": self.registered_subject.dob,
         "initials": self.registered_subject.initials,
         "identity": self.registered_subject.identity,
         "alpha_code": self.requisition.panel_object.alpha_code,
         "panel": self.requisition.panel_object.abbreviation,
         "panel_name": self.requisition.panel.display_name,
     }
示例#16
0
 def load_time_jp(self, timestamp) -> Arrow:
     tz = datetime.timezone(datetime.timedelta(hours=8))
     d_time = datetime.datetime.fromtimestamp(timestamp, tz)
     a_time = Arrow.fromdatetime(d_time)
     if a_time.hour < 4:
         a_time -= datetime.timedelta(hours=4)
     return a_time
 def test_create(self):
     """test create appointment, avoids new years holidays"""
     appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime
     creator = AppointmentCreator(
         subject_identifier=self.subject_identifier,
         visit_schedule_name=self.visit_schedule.name,
         schedule_name=self.schedule.name,
         visit=self.visit1000,
         timepoint_datetime=appt_datetime,
     )
     appointment = creator.appointment
     self.assertEqual(Appointment.objects.all()[0], appointment)
     self.assertEqual(
         Appointment.objects.all()[0].appt_datetime,
         Arrow.fromdatetime(datetime(2017, 1, 3)).datetime,
     )
示例#18
0
    def setUp(self):
        self.subject_identifier = "111111111"
        self.reference_helper = self.reference_helper_cls(
            visit_model=self.visit_model,
            subject_identifier=self.subject_identifier)

        report_datetime = Arrow.fromdatetime(datetime(2017, 7, 7)).datetime
        self.reference_helper.create_visit(
            report_datetime=report_datetime,
            visit_schedule_name="visit_schedule",
            schedule_name="schedule",
            visit_code=DAY1,
            timepoint=Decimal("1.0"),
        )
        self.reference_helper.create_visit(
            report_datetime=report_datetime + relativedelta(days=3),
            visit_schedule_name="visit_schedule",
            schedule_name="schedule",
            visit_code=DAY3,
            timepoint=Decimal("1.0"),
        )
        self.reference_helper.create_visit(
            report_datetime=report_datetime + relativedelta(days=5),
            visit_schedule_name="visit_schedule",
            schedule_name="schedule",
            visit_code=DAY5,
            timepoint=Decimal("1.0"),
        )
示例#19
0
 def _data(self):
     return {
         '_created':
         get_utcnow(),
         'best_prev_result_date':
         self.best_prev_result_date,
         'documented_pos':
         self.documented_pos,
         'documented_pos_date':
         self.documented_pos_date,
         'final_arv_status':
         self.final_arv_status,
         'final_arv_status_baseline':
         self.final_arv_status_baseline,
         'final_hiv_status':
         self.final_hiv_status,
         'final_hiv_status_date':
         self.final_hiv_status_date,
         'has_tested':
         self.has_tested,
         'indeterminate':
         self.indeterminate,
         'known_positive':
         self.known_positive,
         'naive_at_baseline':
         self.naive_at_baseline,
         'newly_diagnosed':
         self.newly_diagnosed,
         'prev_result':
         self.prev_result,
         'prev_result_date':
         self.prev_result_date,
         'prev_result_known':
         self.prev_result_known,
         'prev_results_discordant':
         self.prev_results_discordant,
         'subject_identifier':
         self.subject_identifier,
         'source_object_name':
         self.source_object_name,
         'today_hiv_result':
         self.current.today_hiv_result,
         'baseline_hiv_result':
         self.baseline.today_hiv_result,
         'current_hiv_result':
         self.current.today_hiv_result,
         'self_reported_result':
         self.current.self_reported_result,
         'current_arv_evidence':
         self.current.arv_evidence,
         'declined':
         self.declined,
         'defaulter_at_baseline':
         self.defaulter_at_baseline,
         'visit_code':
         self.subject_visit.visit_code,
         'visit_date':
         Arrow.fromdatetime(self.subject_visit.report_datetime).date(),
     }
 def scheduled_appt_datetime(self):
     scheduled_appt_datetime = None
     if self.scheduled_appt_date:
         dt = self.scheduled_appt_date
         scheduled_appt_datetime = Arrow.fromdatetime(
             datetime(dt.year, dt.month, dt.day, self.default_time.hour,
                      self.default_time.minute)).datetime
     return scheduled_appt_datetime
示例#21
0
 def load_time_cn(self, timestamp) -> Arrow:
     d_time = datetime.datetime.strptime(timestamp,
                                         r"%Y/%m/%d %H:%M")  #mahomaho
     #d_time = datetime.datetime.fromtimestamp(timestamp) #bigfun
     a_time = Arrow.fromdatetime(d_time)
     if a_time.time() < datetime.time(hour=5):
         a_time -= datetime.timedelta(hours=5)
     return a_time
 def validate_not_future_appt_datetime(self):
     appt_datetime = self.cleaned_data.get('appt_datetime')
     if appt_datetime and appt_datetime != NEW_APPT:
         rappt_datetime = Arrow.fromdatetime(
             appt_datetime, appt_datetime.tzinfo)
         if rappt_datetime.to('UTC').date() > get_utcnow().date():
             raise forms.ValidationError({
                 'appt_datetime': 'Cannot be a future date.'})
示例#23
0
def datetime_parser(json_dict):
    date_format = '%Y-%m-%dT%H:%M:%S.%fZ'
    date_format2 = '%Y-%m-%d'
    for (key, value) in json_dict.items():
        if value:
            try:
                dt = datetime.strptime(value, date_format)
                json_dict[key] = Arrow.fromdatetime(dt).datetime
            except TypeError:
                pass
            except ValueError:
                try:
                    dt = datetime.strptime(value[:10], date_format2)
                    json_dict[key] = Arrow.fromdatetime(dt).date()
                except ValueError:
                    pass
    return json_dict
 def validate_not_future_appt_datetime(self):
     appt_datetime = self.cleaned_data.get("appt_datetime")
     if appt_datetime and appt_datetime != NEW_APPT:
         rappt_datetime = Arrow.fromdatetime(appt_datetime,
                                             appt_datetime.tzinfo)
         if rappt_datetime.to("UTC").date() > get_utcnow().date():
             raise forms.ValidationError(
                 {"appt_datetime": "Cannot be a future date."})
示例#25
0
    def __init__(self, datasource, criteria, kind):

        self.datasource = datasource
        self.criteria = criteria
        self.kind = kind

        self.maxcount = 50
        self.hits = -1

        self.querycount = 0

        self.machine = Machine(model=self, states=QueryDateRangeNarrower.states, initial='asleep')

        self.machine.add_transition('start', '*',     'init', after='work')
        self.machine.add_transition('check', '*',     'finished', conditions=['is_ready'])
        self.machine.add_transition('step',  'init',  'finished', conditions='is_century_out_of_bounds')
        self.machine.add_transition('step',  'init',  'whole',  after=['runquery', 'check'])
        self.machine.add_transition('step',  'whole', 'init',  conditions='no_hits', after='range_next_century')


        if self.kind == self.OLDEST:
            self.date_from = Arrow.fromdatetime(datetime.datetime(1800, 01, 01))
            self.date_to   = Arrow.fromdatetime(datetime.datetime(1899, 12, 31))
            self.factor    = +1

            self.machine.add_transition('step',  'whole', 'left',  unless='is_ready', after=['range_whole_left', 'runquery', 'check'])
            self.machine.add_transition('step',  'left',  'right', conditions='no_hits', after=['range_left_right', 'runquery', 'check'])
            self.machine.add_transition('step',  'left',  'whole', unless='is_ready', after=['range_shrink'])
            self.machine.add_transition('step',  'right', 'whole', unless='is_ready', after=['range_shrink'])

        elif self.kind == self.NEWEST:
            self.date_from = Arrow.fromdatetime(datetime.datetime(2000, 01, 01))
            self.date_to   = Arrow.utcnow()
            self.date_to   += relativedelta(months=12-self.date_to.month, days=31-self.date_to.day)
            self.factor    = -1

            self.machine.add_transition('step',  'whole', 'right',  unless='is_ready', after=['range_whole_right', 'runquery', 'check'])
            self.machine.add_transition('step',  'right',  'left', conditions='no_hits', after=['range_right_left', 'runquery', 'check'])
            self.machine.add_transition('step',  'right',  'whole', unless='is_ready', after=['range_shrink'])
            self.machine.add_transition('step',  'left', 'whole', unless='is_ready', after=['range_shrink'])

        else:
            raise ValueError('kind must be self.OLDEST or self.NEWEST')

        self.delta = (self.date_to - self.date_from) / 2
示例#26
0
 def get_day_events(self, match_num) -> tuple:
     if match_num == 2:
         daystr = "今天"
         date = Arrow.now(tzinfo=self.timezone)
     elif match_num == 3:
         daystr = "明天"
         date = Arrow.now(tzinfo=self.timezone) + datetime.timedelta(days=1)
     elif match_num & 0xf00000 == 0x100000:
         year = (match_num & 0xff000) >> 12
         month = (match_num & 0xf00) >> 8
         day = match_num & 0xff
         daystr = "{}年{}月{}日".format(2000 + year, month, day)
         try:
             date = Arrow(2000 + year, month, day)
         except ValueError as v:
             logger.error(f'日期错误{v}')
     events = self.timeline.at(date)
     return (daystr, events)
    def test_create_appt_with_lower_greater_than_zero2(self):
        appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 10)).datetime

        creator = AppointmentCreator(
            subject_identifier=self.subject_identifier,
            visit_schedule_name=self.visit_schedule.name,
            schedule_name=self.schedule.name,
            visit=self.visit1010,
            timepoint_datetime=appt_datetime,
        )
        appointment = Appointment.objects.get(visit_code=self.visit1010.code)
        self.assertEqual(
            Appointment.objects.get(visit_code=self.visit1010.code),
            creator.appointment,
        )
        self.assertEqual(
            appointment.appt_datetime,
            Arrow.fromdatetime(datetime(2017, 1, 10)).datetime,
        )
 def validate_assay_datetime(self, assay_datetime, requisition, field):
     if assay_datetime:
         assay_datetime = Arrow.fromdatetime(
             assay_datetime, assay_datetime.tzinfo).to('utc').datetime
         if assay_datetime < requisition.requisition_datetime:
             formatted = timezone.localtime(requisition.requisition_datetime).strftime(
                 convert_php_dateformat(settings.SHORT_DATETIME_FORMAT))
             raise forms.ValidationError({
                 field: (f'Invalid. Cannot be before date of '
                         f'requisition {formatted}.')})
    def find_tasks_for_time(self,
                            execution_time: Arrow) -> List[SchedulerTask]:
        """
        Finds tasks scheduled for the given time
        :param execution_time: time when the task should be executed
        :type execution_time: arrow
        :return: list of tasks that match the criteria
        :rtype: list
        """
        tasks = []
        """
        OLD CODE
        # In order to compare time, also date has to be added
        # For example 10:00 in Berlin in July is 08:00 UTC, but in December, it would be 09:00 UTC
        # There are several issues with struct_time and conversion to a
        #  datetime. For example, mktime, suggested to convert a struct_time
        #  in local time to a datetime in python doc (see https://docs.python.org/3/library/time.html),
        #  fails miserably on my dev pc because of the underling C
        #  implementation of mktime (more at https://stackoverflow.com/a/2518828)
        # So, in order to overcome this complexity, I'm using Arrow library
        #
        # By default, the EPOC time is used by arrow when converting a
        #  simple time, and everything starts on 1970/01/01 UTC
        # When comparing times near the midnight, with different timezones,
        #  it could happen the time converted in UTC is before the EPOC
        #  start, so Arrow generates a OverflowError. 01:00+03 is an example.
        # To avoid this problem, I always add one day to the original time,
        #  so the corresponding UTC time is always valid

        refer_date = arrow.get(execution_time, "HH:mmZZ").shift(days=1).to("UTC")
        # Drops the date part, keeping only a time converted to UTC, finally
        # a common base for comparisons of all kind
        execution_utc_time_only = refer_date.format("HH:mm ZZ")

        for task in self._tasks:
            # "normalize" the task time in the same way
            check_time = arrow.get(task.when, "HH:mmZZ").shift(days=1).to("UTC")
            if execution_utc_time_only == check_time.format("HH:mm ZZ"):
                tasks.append(task)
        return tasks
        """

        for task in self._tasks:
            # Translate the execution time to the same timezone of the task to
            #  check for
            relative_time = execution_time.to(task.timezone)
            relative_hour = relative_time.hour
            try:
                task_hour = int(task.when[:2])
                if task_hour == relative_hour:
                    tasks.append(task)
            except:
                pass

        return tasks
示例#30
0
 def get_day_events(self, date_num, rg) -> tuple:
     if date_num == 2:
         daystr = "今天"
         date = Arrow.now(tzinfo=self.timezone)
     elif date_num == 3:
         daystr = "明天"
         date = Arrow.now(tzinfo=self.timezone) + datetime.timedelta(days=1)
     elif date_num & 0xf00000 == 0x100000:
         year = (date_num & 0xff000) >> 12
         month = (date_num & 0xf00) >> 8
         day = date_num & 0xff
         daystr = "{}年{}月{}日".format(2000 + year, month, day)
         try:
             date = Arrow(2000 + year, month, day)
         except ValueError as v:
             raise InputError("日期错误:{}".format(v))
     else:
         raise ValueError(f'unespected date_num: {date_num}')
     events = self.timelines[rg].at(date)
     return (daystr, events)
 def validate_requisition_datetime(self):
     requisition_datetime = self.cleaned_data.get('requisition_datetime')
     maternal_visit = self.cleaned_data.get('maternal_visit')
     if requisition_datetime:
         requisition_datetime = Arrow.fromdatetime(
             requisition_datetime, requisition_datetime.tzinfo).to('utc').datetime
         if requisition_datetime < maternal_visit.report_datetime:
             formatted = timezone.localtime(maternal_visit.report_datetime).strftime(
                 convert_php_dateformat(settings.SHORT_DATETIME_FORMAT))
             raise forms.ValidationError({
                 'requisition_datetime':
                 f'Invalid. Cannot be before date of visit {formatted}.'})
 def validate_requisition_datetime(self):
     requisition_datetime = self.cleaned_data.get('requisition_datetime')
     subject_visit = self.cleaned_data.get('subject_visit')
     if requisition_datetime:
         requisition_datetime = Arrow.fromdatetime(
             requisition_datetime, requisition_datetime.tzinfo).to('utc').datetime
         if requisition_datetime < subject_visit.report_datetime:
             formatted = timezone.localtime(subject_visit.report_datetime).strftime(
                 convert_php_dateformat(settings.SHORT_DATETIME_FORMAT))
             raise forms.ValidationError({
                 'requisition_datetime':
                 f'Invalid. Cannot be before date of visit {formatted}.'})
示例#33
0
 def get_week_events(self) -> str:
     reply = "一周日程:"
     date = Arrow.now(tzinfo=self.timezone)
     for i in range(7):
         events = self.timeline.at(date)
         events_str = "\n⨠".join(events)
         if events_str == "":
             events_str = "没有记录"
         daystr = date.format("MM月DD日")
         reply += "\n======{}======\n⨠{}".format(daystr, events_str)
         date += datetime.timedelta(days=1)
     return reply
 def test_create_no_holidays(self):
     for i in range(1, 7):
         appt_datetime = Arrow.fromdatetime(datetime(2017, 1, i)).datetime
     creator = AppointmentCreator(
         subject_identifier=self.subject_identifier,
         visit_schedule_name=self.visit_schedule.name,
         schedule_name=self.schedule.name,
         visit=self.visit1000,
         timepoint_datetime=appt_datetime)
     self.assertEqual(
         Appointment.objects.all()[0], creator.appointment)
     self.assertEqual(
         Appointment.objects.all()[0].appt_datetime, appt_datetime)
 def test_referral_facility_available_datetime_day(self):
     facility = Facility(name='leiden', days=[TU, WE], forward_only=True)
     referral_facility = ReferralFacility(facility=facility,
                                          routine_codes=['MASA-CC'])
     scheduled_appt_datetime = Arrow.fromdate(datetime(2001, 12, 4, 7,
                                                       30)).datetime
     dt = referral_facility.available_datetime(
         referral_code='MASA-CC',
         scheduled_appt_datetime=scheduled_appt_datetime)
     self.assertEqual(weekday(dt.weekday()), TU)
     scheduled_appt_datetime = Arrow.fromdate(datetime(2001, 12, 5, 7,
                                                       30)).datetime
     dt = referral_facility.available_datetime(
         referral_code='MASA-CC',
         scheduled_appt_datetime=scheduled_appt_datetime)
     self.assertEqual(weekday(dt.weekday()), WE)
     scheduled_appt_datetime = Arrow.fromdate(datetime(2001, 12, 6, 7,
                                                       30)).datetime
     dt = referral_facility.available_datetime(
         referral_code='MASA-CC',
         scheduled_appt_datetime=scheduled_appt_datetime)
     self.assertEqual(weekday(dt.weekday()), TU)
 def test_referral_facility_urgent_available_datetime(self):
     """Asserts picks correct date.
     """
     facility = Facility(name='leiden', days=[TU, WE], forward_only=True)
     referral_facility = ReferralFacility(facility=facility,
                                          routine_codes=['MASA-CC'],
                                          urgent_codes=['MASA-DF'])
     # pick a tuesday
     scheduled_appt_datetime = Arrow.fromdate(datetime(2001, 12, 4, 7,
                                                       30)).datetime
     # pick a wednesday
     report_datetime = Arrow.fromdate(datetime(2001, 12, 5, 7, 30)).datetime
     dt = referral_facility.available_datetime(
         referral_code='MASA-CC',
         scheduled_appt_datetime=scheduled_appt_datetime,
         report_datetime=report_datetime)
     self.assertEqual(dt, scheduled_appt_datetime)
     dt = referral_facility.available_datetime(
         referral_code='MASA-DF',
         scheduled_appt_datetime=scheduled_appt_datetime,
         report_datetime=report_datetime)
     self.assertEqual(dt, report_datetime)
示例#37
0
    def on(self, day: Arrow, strict: bool = False) -> Iterator[Event]:
        """Iterates (in chronological order) over all events that occurs on `day`

        Args:
            day (Arrow object)
            strict (bool): if True events will be returned only if they are\
            strictly *included* in `day`.
        """
        day_start, day_stop = day.floor('day').span('day')
        if strict:
            return self.included(day_start, day_stop)
        else:
            return self.overlapping(day_start, day_stop)
示例#38
0
    def arrow(self, date=None, tz=None):

        if date is None:
            return self.utcnow() if tz is None else self.now(tz)

        else:

            if tz is None:
                try:
                    tz = parser.TzinfoParser.parse(date)
                    return self.now(tz)
                except:
                    pass

                if isinstance(date, (float, int)):
                    return Arrow.utcfromtimestamp(date)

                return Arrow.fromdatetime(date)

            else:

                tz = parser.TzinfoParser.parse(tz)
                return Arrow.fromdatetime(date, tz)
示例#39
0
    def test_record_update(self):

        create_class(ClassToUpdate, client=self.client)

        class_to_update = ClassToUpdate()
        class_to_update.int_field = 10
        class_to_update.str_field = 'foobar'
        class_to_update.datetime_field = Arrow.utcnow()
        class_to_update.float_field = 12345.547
        insert(class_to_update, client=self.client)
        self.assertIsNotNone(class_to_update.rid)
        r = load(class_to_update.rid, client=self.client)
        self.assertEqual(r._rid, class_to_update.rid)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['str_field']],
                         class_to_update.str_field)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['int_field']],
                         class_to_update.int_field)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['datetime_field']],
                         class_to_update.datetime_field.timestamp)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['float_field']],
                         class_to_update.float_field)
        class_to_update.int_field = 20
        class_to_update.str_field = 'barfoo'
        class_to_update.datetime_field = Arrow.utcnow()
        class_to_update.float_field = None
        update(class_to_update, client=self.client)
        self.assertIsNotNone(class_to_update.rid)
        r = load(class_to_update.rid, client=self.client)
        self.assertEqual(r._rid, class_to_update.rid)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['str_field']],
                         class_to_update.str_field)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['int_field']],
                         class_to_update.int_field)
        self.assertEqual(r.oRecordData[class_to_update._py_to_orient_field_mapping['datetime_field']],
                         class_to_update.datetime_field.timestamp)
        self.assertFalse(class_to_update._py_to_orient_field_mapping['float_field'] in r.oRecordData)
示例#40
0
 def test_from_orient(self):
     
     create_class(ClassToInsert, client=self.client)
     
     class_to_insert = ClassToInsert()
     class_to_insert.int_field = 10
     class_to_insert.str_field = 'foobar'
     class_to_insert.datetime_field = Arrow.utcnow()
     class_to_insert.float_field = 12345.547
     class_to_insert.bin_field = bytes('foo','utf-8')
     insert(class_to_insert, client=self.client)
     r = load(class_to_insert.rid, client=self.client)
     result = Model.from_orient(r)
     self.assertEqual(class_to_insert.__class__, result.__class__)
     self.assertEqual(result.rid, class_to_insert.rid)
     self.assertEqual(result.str_field, class_to_insert.str_field)
     self.assertEqual(result.int_field, class_to_insert.int_field)
     self.assertEqual(result.datetime_field, class_to_insert.datetime_field)
     self.assertEqual(result.float_field, class_to_insert.float_field)
     self.assertEqual(result.bin_field, class_to_insert.bin_field)
示例#41
0
 def test_get(self):
     
     create_class(ClassToGet, client=self.client)
     
     class_to_insert = ClassToGet()
     class_to_insert.int_field = 10
     class_to_insert.str_field = 'foobar'
     class_to_insert.datetime_field = Arrow.utcnow()
     class_to_insert.float_field = 12345.547
     class_to_insert.bin_field = bytes('foo','utf-8')
     class_to_insert.bool_field = True
     insert(class_to_insert, client=self.client)
     loaded_class = ClassToGet.get(class_to_insert.rid, client=self.client)
     self.assertEqual(class_to_insert.__class__, loaded_class.__class__)
     self.assertEqual(loaded_class.rid, class_to_insert.rid)
     self.assertEqual(loaded_class.str_field, class_to_insert.str_field)
     self.assertEqual(loaded_class.int_field, class_to_insert.int_field)
     self.assertEqual(loaded_class.datetime_field, class_to_insert.datetime_field)
     self.assertEqual(loaded_class.float_field, class_to_insert.float_field)
     self.assertEqual(loaded_class.bin_field, class_to_insert.bin_field)
     self.assertEqual(loaded_class.bool_field, class_to_insert.bool_field)
 def label_context(self):
     edc_protocol_app_config = django_apps.get_app_config('edc_protocol')
     utc = Arrow.fromdatetime(
         self.requisition.drawn_datetime or self.requisition.created)
     dte = utc.to(settings.TIME_ZONE).datetime
     formatted_date = dte.strftime("%Y-%m-%d %H:%M")
     printed = 'PRINTED: ' if not self.requisition.drawn_datetime else 'DRAWN: '
     return {
         'requisition_identifier': self.requisition.requisition_identifier,
         'item': self.item,
         'item_count': self.requisition.item_count or 1,
         'primary': '<P>',
         'barcode_value': self.requisition.requisition_identifier,
         'protocol': edc_protocol_app_config.protocol,
         'site': str(self.requisition.site.id),
         'site_name': str(self.requisition.site.name),
         'clinician_initials': self.user.username[0:2].upper(),
         'drawn_datetime': f'{printed}{formatted_date}',
         'subject_identifier': self.registered_subject.subject_identifier,
         'gender': self.registered_subject.gender,
         'dob': self.registered_subject.dob,
         'initials': self.registered_subject.initials,
         'alpha_code': self.requisition.panel_object.alpha_code,
         'panel': self.requisition.panel_object.abbreviation}
示例#43
0
    def test_load_record(self):

        create_class(ClassToLoad, client=self.client)

        class_to_insert = ClassToLoad()
        class_to_insert.int_field = 10
        class_to_insert.str_field = 'foobar'
        class_to_insert.datetime_field = Arrow.utcnow()
        class_to_insert.float_field = 12345.547
        class_to_insert.bin_field = bytes('foo', 'utf-8')
        insert(class_to_insert, client=self.client)
        self.assertIsNotNone(class_to_insert.rid)
        r = load(class_to_insert.rid, client=self.client)
        self.assertEqual(r._rid, class_to_insert.rid)
        self.assertEqual(r.oRecordData[class_to_insert._py_to_orient_field_mapping['str_field']],
                         class_to_insert.str_field)
        self.assertEqual(r.oRecordData[class_to_insert._py_to_orient_field_mapping['int_field']],
                         class_to_insert.int_field)
        self.assertEqual(r.oRecordData[class_to_insert._py_to_orient_field_mapping['datetime_field']],
                         class_to_insert.datetime_field.timestamp)
        self.assertEqual(r.oRecordData[class_to_insert._py_to_orient_field_mapping['float_field']],
                         class_to_insert.float_field)
        self.assertEqual(base64.b64decode(r.oRecordData[class_to_insert._py_to_orient_field_mapping['bin_field']].encode()),
                         class_to_insert.bin_field)
示例#44
0
#!/usr/bin/env python

from functools import reduce

from base64 import urlsafe_b64encode
from uuid import uuid4

from requests import Session
from requests.adapters import HTTPAdapter
from urllib.parse import urlparse, urlunparse

from datetime import datetime, timedelta
from arrow.arrow import Arrow
dt_arrow = lambda dt: Arrow.fromdatetime(dt)

from ics import Calendar as CalendarBase, Event
from ics.timeline import Timeline

import logging
log = logging.getLogger('calenvite.calenvite')

from calenvite.exceptions import ResourceNotFound, ResourceConflict

DEFAULT_DOMAIN='localhost'


class WebcalAdapter(HTTPAdapter):
    def get_connection(self, url, proxies=None):
        url = 'http'+url[6:] if url.startswith('webcal') else url
        return super().get_connection(url, proxies)