Example #1
0
 def run(self, task_define):
     Arrow.now().date()
     start_dt = arrow.get(task_define['last_crawl_day'])  # .strftime('%Y%m%d')
     end_dt = arrow.get(task_define['cur_dt'])
     for r_dt in Arrow.range('day', start_dt, end_dt):
         logger.info('Start to crawl data of task: %s, dt: %s' % (self.__class__.__name__, r_dt))
         t_dt = r_dt.strftime('%Y%m%d')
         daily_records = self.ts_client.query(API_NAME, trade_date=t_dt)
         self.write_db_with_df('stock_daily_basic', daily_records)
Example #2
0
def get_for(date):
    date = date.replace(tzinfo='utc')
    for week in get_dates(access_token):
        for day, visits in week:
            if day == date:
                return VisitResult(
                    visits,      # visits for day
                    Arrow.now(AU_PERTH)  # when data was retrieved
                )
    return VisitResult([], Arrow.now(AU_PERTH))
Example #3
0
def test_order_pending():
    uuid1, uuid2 = uuid4(), uuid4()

    ordering = Ordering(mock.Mock())
    ordering.pending_orders[uuid1] = Arrow.now()
    ordering.pending_orders[uuid2] = Arrow.now()

    ordering.order_pending()

    assert ordering.ordering_publisher.ship.call_count == 2
Example #4
0
def test_add_pending_shipment_one_order_per_uuid():
    uuid_1 = uuid4()
    uuid_2 = UUID(uuid_1.hex)
    ordering = Ordering(mock.Mock())

    ordering.add_pending_shipment(uuid_1, Arrow.now())
    ordering.add_pending_shipment(uuid_2, Arrow.now())

    assert len(ordering.pending_orders) == 1
    assert ordering.pending_orders[uuid_1.hex]
Example #5
0
def cached_get_for(date):
    if not hasattr(cached_get_for, '_cache'):
        cached_get_for._cache = {}

    if date in cached_get_for._cache:
        data, timestamp = cached_get_for._cache[date]

        if (Arrow.now() - timestamp) < timedelta(hours=1):
            return data

    cached_get_for._cache[date] = (get_for(date), Arrow.now())
    return cached_get_for._cache[date][0]
Example #6
0
def get_xml(item, items):
    root = ET.Element('rss')
    root.attrib = {'version': "2.0"}
    c = ET.SubElement(root, 'channel')
    ET.SubElement(c, 'copyright').text = 'Copyright 2016, Liu Vaayne'
    if item.get('source_name') == 'wx':
        ET.SubElement(c, 'title').text = item.get('author')
    else:
        ET.SubElement(c, 'title').text = item.get('title')
    ET.SubElement(c, 'link').text = item.get('link')
    ET.SubElement(c, 'description').text = item.get('desc')
    ET.SubElement(c, 'lastBuildDate').text = Arrow.now().format('YYYY-MM-DD HH:mm:ss')
    for item in items:
        i = ET.SubElement(c, 'item')
        ET.SubElement(i, 'title').text = item.get('title')
        # ET.SubElement(i, 'image').text = item.get('image')
        # ET.SubElement(i, 'pubDate').text = datetime.datetime.fromtimestamp(int(item.get('post_time')))
        ET.SubElement(i, 'pubDate').text = item.get('post_time').strftime('%Y-%m-%d %H:%M:%S')
        ET.SubElement(i, 'link').text = item.get('source_url')
        # ET.SubElement(i, 'summary').text = item.get('summary')
        # ET.SubElement(i, 'description').text = item.get('content')
        ET.SubElement(i, 'category').text = item.get('category')
    tree = ET.ElementTree(root)
    f = StringIO()
    tree.write(sys.stdout)
    print (f.getvalue())
    return f.getvalue()
Example #7
0
    async def get_events(self, num=10, page=0, more=False, weekend=False):
        logger.debug("cogs/f1/get_events: Fetching",
                     num=num,
                     more=more,
                     weekend=weekend)
        lines = []
        calendar = await self.calendar()
        timeline = list(calendar.timeline.start_after(Arrow.now()))
        start = min(page * num, len(timeline) - num)

        logger.info("cogs/f1/get_events",
                    start=start,
                    len_timeline=len(timeline))

        for event in list(calendar.timeline.now()):
            lines.append(
                f"**{event.name}** ongoing, ending " +
                human(event.end.to(SUPER_TIMEZONE).timestamp, precision=2))

        for event in list(timeline)[start:]:
            local_time = event.begin.to(SUPER_TIMEZONE)
            lines.append("**{0}** {1}, {2}".format(
                event.name,
                human(local_time.timestamp, precision=2),
                local_time.strftime("%d %b @ %H:%M"),
            ))
            if len(lines) >= num or weekend and local_time.isoweekday() in (7,
                                                                            1):
                break
        if more and len(timeline) - start - num:
            lines.append(f"...and {len(timeline) - start - num} more")
        logger.info("cogs/f1/get_events: Fetched", result=lines)
        return lines
Example #8
0
File: api.py Project: gurglet/arrow
def now(tz=None):
    '''Returns an :class:`Arrow <arrow.Arrow>` object, representing "now".

    :param tz: (optional) An expression representing a timezone.  Defaults to local time.

    Recognized timezone expressions:

        - A **tzinfo** object
        - A **str** describing a timezone, similar to "US/Pacific", or "Europe/Berlin"
        - A **str** in ISO-8601 style, as in "+07:00"
        - A **str**, one of the following:  *local*, *utc*, *UTC*

    Usage::

        >>> import arrow
        >>> arrow.now()
        <Arrow [2013-05-07T22:19:11.363410-07:00]>

        >>> arrow.now('US/Pacific')
        <Arrow [2013-05-07T22:19:15.251821-07:00]>

        >>> arrow.now('+02:00')
        <Arrow [2013-05-08T07:19:25.618646+02:00]>

        >>> arrow.now('local')
        <Arrow [2013-05-07T22:19:39.130059-07:00]>
    '''

    if tz is None:
        tz = dateutil_tz.tzlocal()
    elif not isinstance(tz, tzinfo):
        tz = parser.TzinfoParser.parse(tz)

    return Arrow.now(tz)
Example #9
0
def now(tz=None):
    '''Returns an :class:`Arrow <arrow.Arrow>` object, representing "now".

    :param tz: (optional) An expression representing a timezone.  Defaults to local time.

    The timezone expression can be:

        - A tzinfo struct
        - A string description, e.g. "US/Pacific", or "Europe/Berlin"
        - An ISO-8601 string, e.g. "+07:00"
        - A special string, one of:  "local", "utc", or "UTC"

    Usage::

        >>> import arrow
        >>> arrow.now()
        <Arrow [2013-05-07T22:19:11.363410-07:00]>
        >>> arrow.now('US/Pacific')
        <Arrow [2013-05-07T22:19:15.251821-07:00]>
        >>> arrow.now('+02:00')
        <Arrow [2013-05-08T07:19:25.618646+02:00]>
        >>> arrow.now('local')
        <Arrow [2013-05-07T22:19:39.130059-07:00]>
    '''

    if tz is None:
        tz = dateutil_tz.tzlocal()
    elif not isinstance(tz, tzinfo):
        tz = parser.TzinfoParser.parse(tz)

    return Arrow.now(tz)
Example #10
0
 def get_course_list(self):
     # 获取课程状态
     if not self.__session:
         raise AttributeError('未获取有效的session对象')  # TODO 此sesseion判断并不严谨,需更改
     result = []
     now = int(Arrow.now().float_timestamp * 1000)  # generate javascript style timestamp
     _response = self.__session.get(
         'http://www.elearning.clic/ilearn/en/cst_learner2/jsp/home_my_course.jsp?_={time}'.format(
             time=now))  # 取得课程信息
     root = etree.HTML(_response.text)
     td_list = root.xpath(u'//span[@class="td_td_style"]')  # 查找有效表格
     a_list = root.xpath(u'//a[@title="Click to study"]')  # 查找有效课程url
     td_len = len(td_list)  # 取得有效td元素个数
     a_len = len(a_list)  # 取得有效链接个数
     if td_len is not 0 and a_len is not 0:
         # 如果找到有效td元素和a元素,就以每4组td生成一个字典
         for n in range(int(td_len / 4)):
             sub = 0 * n
             result.append({
                 'course_name': td_list[sub].text.strip(),
                 'course_section_rate': float(td_list[sub + 1].text.strip().partition('\n')[0]),
                 'course_time_rate': float(td_list[sub + 2].text.strip().partition('\n')[0]),
                 'course_finished': td_list[sub + 3].text.strip() == '已完成',
                 'course_url': a_list[n].attrib['href']
             })
     self.last_response = _response
     self.__course = result
     for k, v in enumerate(result):
         print('序号:{0} \t课名: {1}\t课程进度: {2}\t课时进度: {3}\t完成: {4}\n'.format(k, v['course_name'],
                                                                          v['course_section_rate'],
                                                                          v['course_time_rate'],
                                                                          v['course_finished'] is True))
Example #11
0
def get_xml(item, items):
    root = ET.Element('rss')
    root.attrib = {'version': "2.0"}
    c = ET.SubElement(root, 'channel')
    ET.SubElement(c, 'copyright').text = 'Copyright 2016, Liu Vaayne'
    if item.get('source_name') == 'wx':
        ET.SubElement(c, 'title').text = item.get('author')
    else:
        ET.SubElement(c, 'title').text = item.get('title')
    ET.SubElement(c, 'link').text = item.get('link')
    ET.SubElement(c, 'description').text = item.get('desc')
    ET.SubElement(
        c, 'lastBuildDate').text = Arrow.now().format('YYYY-MM-DD HH:mm:ss')
    for item in items:
        i = ET.SubElement(c, 'item')
        ET.SubElement(i, 'title').text = item.get('title')
        # ET.SubElement(i, 'image').text = item.get('image')
        # ET.SubElement(i, 'pubDate').text = datetime.datetime.fromtimestamp(int(item.get('post_time')))
        ET.SubElement(i, 'pubDate').text = item.get('post_time').strftime(
            '%Y-%m-%d %H:%M:%S')
        ET.SubElement(i, 'link').text = item.get('source_url')
        # ET.SubElement(i, 'summary').text = item.get('summary')
        # ET.SubElement(i, 'description').text = item.get('content')
        ET.SubElement(i, 'category').text = item.get('category')
    tree = ET.ElementTree(root)
    f = StringIO()
    tree.write(sys.stdout)
    print(f.getvalue())
    return f.getvalue()
Example #12
0
    def __init__(self,
                 client: "ProtosBot",
                 channel: "TextChannel",
                 pattern: str,
                 last: Arrow = Arrow.now()):
        """
        Create a new job.

        client is the bot instance.
        channel is the text channel this job should run in.
        pattern is the pattern of checks to execute against messages.
        last is the last time this job was executed.
        """

        self.client = client
        self.channel = channel
        self.pattern = json.loads(pattern)
        self.last = last

        self._conditions = set()
        self._parse_pattern(self.pattern)

        if not self._conditions:
            raise MalformedPatternException(
                "Must specify at least one condition.")
Example #13
0
File: uptime.py Project: K900/m5
def get_uptime(message):
    """
    Get uptime, code reload time and crash counts this session
    Usage: uptime
    """
    now = Arrow.now()
    reply('''{}

Way status:
    [ ] Lost
    [X] Not lost

Holding on since:
    {}
Uptime:
    {}
Last code reload:
    {}
Code uptime:
    {}

Total crashes this session: {}
    '''.format(
        VERSION_STRING,
        uptime.humanize(),
        now - uptime,
        code_uptime.humanize(),
        now - code_uptime,
        crash_count
    ), message)
Example #14
0
def test_shipment_ordered():
    uuid = uuid4()
    ordering = Ordering(mock.Mock())
    ordering.pending_orders[uuid.hex] = Arrow.now()

    ordering.shipment_ordered(uuid)

    assert len(ordering.pending_orders) == 0
Example #15
0
def test_add_pending_shipment_adds_pending_order():
    uuid = uuid4()
    now = Arrow.now()
    ordering = Ordering(mock.Mock())

    ordering.add_pending_shipment(uuid, now)

    assert ordering.pending_orders[uuid.hex] == now
Example #16
0
 def get_datestr_and_dateint(self, datestr_area):
     time_str = re.match(ur'(\d{4})年 (\d{1,2})月 (\d{1,2})日.+?(\d{2}):(\d{2})', datestr_area).groups()
     time_str = map(int, time_str)
     src_time = Arrow.now().replace(year=time_str[0], month=time_str[1], day=time_str[2], hour=time_str[3],
                                    minute=time_str[4], second=0).timestamp
     return dict(
         datestr=datestr_area,
         dateint=src_time
     )
Example #17
0
    async def __call__(self) -> int:
        def check(msg):
            for condition in self._conditions:
                if not condition(self, msg):
                    return False
            return True

        c = await self.channel.purge(check=check)

        self.last = Arrow.now()

        return len(c)
Example #18
0
 def get_time_humanized(self):
     now = self.created
     otherdate = datetime.now()
     if otherdate:
         dt = otherdate - now
         offset = dt.seconds + (dt.days * 60*60*24)
     if offset:
         delta_s = offset % 60
         offset /= 60
         delta_m = offset % 60
         offset /= 60
         delta_h = offset % 24
         offset /= 24
         delta_d = offset
     else:
         return "just now"
     if delta_h > 1:
         return Arrow.now().replace(hours=delta_h * -1, minutes=delta_m * -1).humanize()
     if delta_m > 1:
         return Arrow.now().replace(seconds=delta_s * -1, minutes=delta_m * -1).humanize()
     else:
         return Arrow.now().replace(days=delta_d * -1).humanize()
Example #19
0
 def get_datestr_and_dateint(self, datestr_area):
     rt = dict(datestr='', dateint=0)
     if isinstance(datestr_area, unicode) or isinstance(datestr_area, str):
         for time_re, arrow_fmt in time_formats:
             findall = time_re.findall(datestr_area)
             if findall:
                 ar = Arrow.strptime(findall[0].encode('utf8'), arrow_fmt,
                                     'Asia/Shanghai')
                 if ar.year < 2000:
                     ar = ar.replace(year=Arrow.now().datetime.year)
                 rt = dict(datestr=findall[0], dateint=ar.timestamp)
                 break
     return rt
Example #20
0
 def save_course(self):
     # 保存课时
     save_data = {
         'callCount': 1,
         'page': '/ilearn/en/learner/jsp/player/player_left.jsp?rco_id={0}'.format(self.__save_dict.get('rco_id')),
         'httpSessionId': self.last_response.cookies.get('JSESSIONID'),
         'scriptSessionId': self.__script_session_id,
         'c0-scriptName': 'lessonStudyData',
         'c0-methodName': 'updateRcoTreeList',
         'c0-id': 0,
         'c0-e1': 'string:' + self.__save_dict.get('rco_id'),
         'c0-e2': 'string:' + self.__save_dict.get('curr_rco_id'),
         'c0-e3': 'string:' + self.__save_dict.get('curr_rco_id'),
         'c0-e4': 'string:' + self.__save_dict.get('icr_id'),
         'c0-e5': 'string:' + self.__save_dict.get('user_id'),
         'c0-e6': 'string:' + self.__save_dict.get('tbc_id'),
         'c0-e7': 'string:' + self.__save_dict.get('site_id'),
         'c0-e8': 'string:' + self.__save_dict.get('cmi_core_lesson_status'),
         'c0-e9': 'string:' + self.__save_dict.get('cmi_core_score_raw'),
         'c0-e10': 'string:' + self.__save_dict.get('cmi_core_lesson_location'),
         'c0-e11': 'string:' + self.__save_dict.get('cmi_suspend_data'),
         'c0-e12': 'string:' + self.__save_dict.get('cmi_core_session_time'),
         'c0-e13': 'string:' + self.__save_dict.get('cmi_mastery_score'),
         'c0-e14': 'string:' + self.__save_dict.get('cmi_core_credit'),
         'c0-e15': 'string:' + quote(self.__save_dict.get('start_time')),
         'c0-e16': 'string:' + quote(Arrow.now().isoformat(sep='\u0020').split('.')[0]),
         'c0-e17': 'string:' + self.__save_dict.get('pre_score'),
         'c0-e18': 'string:' + self.__save_dict.get('pre_status'),
         'c0-e19': 'string:' + self.__save_dict.get('pre_location'),
         'c0-e20': 'string:' + self.__save_dict.get('pre_suspend_data'),
         'c0-e21': 'string:' + self.__save_dict.get('effectivelength'),
         'c0-e22': 'string:' + self.__save_dict.get('is_lesson_time'),
         'c0-e23': 'string:' + self.__save_dict.get('tracking_type'),
         'c0-e24': 'string:' + self.__save_dict.get('attempt_num_flag'),
         'c0-param0': 'Object_Object:{rco_id:reference:c0-e1, pre_rco_id:reference:c0-e2, curr_rco_id:reference:c0-e3, icr_id:reference:c0-e4, user_id:reference:c0-e5, tbc_id:reference:c0-e6, site_id:reference:c0-e7, cmi_core_lesson_status:reference:c0-e8, cmi_core_score_raw:reference:c0-e9, cmi_core_lesson_location:reference:c0-e10, cmi_suspend_data:reference:c0-e11, cmi_core_session_time:reference:c0-e12, cmi_mastery_score:reference:c0-e13, cmi_core_credit:reference:c0-e14, start_time:reference:c0-e15, start_study_time:reference:c0-e16, pre_score:reference:c0-e17, pre_status:reference:c0-e18, pre_location:reference:c0-e19, pre_suspend_data:reference:c0-e20, effectivelength:reference:c0-e21, is_lesson_time:reference:c0-e22, tracking_type:reference:c0-e23, attempt_num_flag:reference:c0-e24}',
         'c0-param1': 'string:U',
         'batchId': self.__batch_id
     }
     self.__batch_id += 1
     _response = self.__session.post(
         'http://www.elearning.clic/ilearn/dwr/call/plaincall/lessonStudyData.updateRcoTreeList.dwr',
         save_data)
     self.last_response = _response
Example #21
0
def get_date_from_request():
    date = request.args.get('date')

    if date is not None:
        try:
            date = get_date(date)
        except (ValueError, TypeError, ParserError):
            pass

    if date == 'today':
        date = Arrow.now(AU_PERTH)

    if date is not None:
        try:
            date = date.floor('day')
        except AttributeError:
            # was invalid and stayed a string
            date = None

    return date
Example #22
0
def index():
    date = get_date_from_request()

    if date is None:
        # fill in missing values with defaults
        return redirect(url_for('.index', date='today'))

    visits, updated = get_visits_for_date(date)
    visits = sorted(visits.items())
    is_today = date.date() == Arrow.now(AU_PERTH).date()

    return render_template(
        'index.html',
        date=date,
        visits=visits,
        locations=LOCATIONS,
        updated=updated,
        is_today=is_today,
        next_page=make_link(date + ONE_DAY),
        prev_page=make_link(date - ONE_DAY)
    )
Example #23
0
def create_new_room(event, context) -> Dict[str, str]:
    now = Arrow.now()
    while True:
        room_id = utils.get_random_string(ROOM_ID_LENGTH)
        if not repo.query_room(room_id):
            break
    room = repo.initialize_room(Room(room_id), now)
    # try:
    #     room = repo.initialize_room(Room(room_id), now)
    # except RuntimeError as e:
    #     print("サーバ側のエラーです。", e)
    #     res["errorCode"] = ""
    # except ConnectionError as e:
    #     print()
    body = str(room)
    return {
        'statusCode': 200,
        'headers': {
            'Location': '{}'.format()
        },
        'body': json.dumps(body),
        'isBase64Encoded': False
    }
Example #24
0
    def check(self, last):

        return last.shift(seconds=self.time) < Arrow.now()
Example #25
0
    def __call__(self, job, msg):

        return arrow.get(
            msg.created_at) < Arrow.now().shift(seconds=-self.time)
Example #26
0
def calendar(tdb: TaskDB, period="month") -> None:
    assert period in ["month", "week"]
    date = Arrow.now()
    tasks = _calendar_tasks(tdb, date, period)
    _calendar_print(tasks, date)
Example #27
0
File: api.py Project: gurglet/arrow
def get(*args, **kwargs):
    '''Returns an :class:`Arrow <arrow.Arrow>` object based on flexible inputs.

    Usage::

        >>> import arrow

    **No inputs** to get current UTC time::

        >>> arrow.get()
        <Arrow [2013-05-08T05:51:43.316458+00:00]>

    **One str**, **float**, or **int**, convertible to a floating-point timestamp, to get that timestamp in UTC::

        >>> arrow.get(1367992474.293378)
        <Arrow [2013-05-08T05:54:34.293378+00:00]>

        >>> arrow.get(1367992474)
        <Arrow [2013-05-08T05:54:34+00:00]>

        >>> arrow.get('1367992474.293378')
        <Arrow [2013-05-08T05:54:34.293378+00:00]>

        >>> arrow.get('1367992474')
        <Arrow [2013-05-08T05:54:34+00:00]>

    **One str**, convertible to a timezone, or **tzinfo**, to get the current time in that timezone::

        >>> arrow.get('local')
        <Arrow [2013-05-07T22:57:11.793643-07:00]>

        >>> arrow.get('US/Pacific')
        <Arrow [2013-05-07T22:57:15.609802-07:00]>

        >>> arrow.get('-07:00')
        <Arrow [2013-05-07T22:57:22.777398-07:00]>

        >>> arrow.get(tz.tzlocal())
        <Arrow [2013-05-07T22:57:28.484717-07:00]>

    **One** naive **datetime**, to get that datetime in UTC::

        >>> arrow.get(datetime(2013, 5, 5))
        <Arrow [2013-05-05T00:00:00+00:00]>

    **One** aware **datetime**, to get that datetime::

        >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal()))
        <Arrow [2013-05-05T00:00:00-07:00]>

    **Two** arguments, a naive or aware **datetime**, and a timezone expression (as above)::

        >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific')
        <Arrow [2013-05-05T00:00:00-07:00]>

    **Two** arguments, both **str**, to parse the first according to the format of the second::

        >>> arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss')
        <Arrow [2013-05-05T12:30:45+00:00]>

    **Three or more** arguments, as for the constructor of a **datetime**::

        >>> arrow.get(2013, 5, 5, 12, 30, 45)
        <Arrow [2013-05-05T12:30:45+00:00]>
    '''

    arg_count = len(args)

    if arg_count == 0:
        return Arrow.utcnow()

    if arg_count == 1:
        arg = args[0]
        timestamp = None

        try:
            timestamp = float(arg)
        except:
            pass

        # (int), (float), (str(int)) or (str(float)) -> from timestamp.
        if timestamp is not None:
            return Arrow.utcfromtimestamp(timestamp)

        # (datetime) -> from datetime.
        elif isinstance(arg, datetime):
            return Arrow.fromdatetime(arg)

        # (tzinfo) -> now, @ tzinfo.
        elif isinstance(arg, tzinfo):
            return Arrow.now(arg)

        # (str) -> now, @ tzinfo.
        elif isinstance(arg, str):
            _tzinfo = parser.TzinfoParser.parse(arg)
            return Arrow.now(_tzinfo)

        else:
            raise TypeError('Can\'t parse single argument type of \'{0}\''.format(type(arg)))

    elif arg_count == 2:

        arg_1, arg_2 = args[0], args[1]

        if isinstance(arg_1, datetime):

            # (datetime, tzinfo) -> fromdatetime @ tzinfo.
            if isinstance(arg_2, tzinfo):
                return Arrow.fromdatetime(arg_1, arg_2)

            # (datetime, str) -> fromdatetime @ tzinfo.
            elif isinstance(arg_2, str):
                _tzinfo = parser.TzinfoParser.parse(arg_2)
                return Arrow.fromdatetime(arg_1, _tzinfo)

            else:
                raise TypeError('Can\'t parse two arguments of types \'datetime\', \'{0}\''.format(
                    type(arg_2)))

        # (str, format) -> parsed.
        elif isinstance(arg_1, str) and isinstance(arg_2, str):
            dt = parser.DateTimeParser.parse(args[0], args[1])
            return Arrow.fromdatetime(dt)

        else:
            raise TypeError('Can\'t parse two arguments of types \'{0}\', \'{1}\''.format(
                type(arg_1), type(arg_2)))

    # 3+ args.
    else:
        return Arrow(*args, **kwargs)
Example #28
0
File: uptime.py Project: K900/m5
from arrow import Arrow
from m5.core.dispatcher import on
from m5.core.event.messaging import reply
from m5.core.meta import VERSION_STRING
from m5.plugins.command_dispatcher import command

try:
    # noinspection PyUnboundLocalVariable,PyUnresolvedReferences
    uptime
except NameError:
    uptime = Arrow.now()

try:
    # noinspection PyUnboundLocalVariable
    crash_count
except NameError:
    crash_count = 0

code_uptime = Arrow.now()


@on('crash')
def crash(_):
    global crash_count
    crash_count += 1


@command('uptime')
def get_uptime(message):
    """
    Get uptime, code reload time and crash counts this session
Example #29
0
 def order_pending(self) -> None:
     print("Ordering pending items if present")
     for uuid in self.pending_orders:
         self.ordering_publisher.ship(
             CreateShipment(MessageTypes.create_shipment, uuid4(),
                            Arrow.now(), 'DHL', uuid))
Example #30
0
def holmes_place_now():
    """
    Returns now in Israel TZ.
    This is the Timezone Holmes Place uses.
    """
    return Arrow.now(tzinfo=ISRAEL_TZ)
Example #31
0
        def test_dehumanize_vanilla(self):
            """Make sure we don't break vanilla Arrow.dehumanize() functionality"""
            log.title('TestXArrow.Test_dehumanize.test_dehumanize_vanilla')
            now = XArrow.now()
            now_dehumanized = XArrow.dehumanize("now")
            assert_arrows_soft_eq(now_dehumanized, now)
            assert_arrows_soft_eq(XArrow.dehumanize("just now"), now)
            # * 1 unit
            # "hour": "an hour", "days": "{0} days"
            for unit, expression in EnglishLocale.timeframes.items():
                for relative_fmt in ("{0} ago", "in {0}"):
                    if 'now' in expression:
                        continue
                    if '{0}' in expression:
                        shift = randint(2, 4)
                        hardcoded_number = expression.format(
                            shift)  # 3 seconds
                        human_expression = relative_fmt.format(
                            hardcoded_number)  # 3 seconds ago / in 3 seconds
                    else:
                        shift = 1
                        human_expression = relative_fmt.format(
                            expression)  # a second ago / in a second
                    dehumanized_static = XArrow.dehumanize(human_expression)

                    if 'ago' in relative_fmt:
                        shift *= -1
                    shift_kwargs = {unit.removesuffix('s') + 's': shift}
                    now = XArrow.now()
                    now_shifted = now.shift(**shift_kwargs)
                    try:
                        assert_arrows_soft_eq(dehumanized_static, now_shifted)
                    except AssertionError:
                        dehumanized_static = XArrow.dehumanize(
                            human_expression)
                        now = XArrow.now()
                        now_shifted = now.shift(**shift_kwargs)
                        assert_arrows_soft_eq(dehumanized_static, now_shifted)

                    dehumanized_instance = now.dehumanize(human_expression)
                    assert_arrows_soft_eq(dehumanized_instance, now_shifted)

            # * 2 units
            for time_unit_1 in TIME_UNITS:
                for time_unit_2 in TIME_UNITS:
                    if time_unit_1 == time_unit_2:
                        continue
                    if random() < 0.5:
                        continue
                    shift_1 = randint(2, 4)
                    shift_2 = randint(2, 4)
                    singular_time_unit_1 = (f"a" if time_unit_1 != "hour" else
                                            "an") + f" {time_unit_1}"
                    singular_time_unit_2 = (f"a" if time_unit_2 != "hour" else
                                            "an") + f" {time_unit_2}"
                    plural_time_unit_1 = f"{shift_1} {time_unit_1}s"
                    plural_time_unit_2 = f"{shift_2} {time_unit_2}s"
                    expressions = {}
                    for fmt in ["{0} and {1}", "{0}, {1}", "{0} {1}"]:
                        expressions[
                            fmt.format(plural_time_unit_1, plural_time_unit_2)
                            + " ago"] = (True, True)
                        expressions["in " + fmt.format(
                            plural_time_unit_1, plural_time_unit_2)] = (True,
                                                                        True)
                        expressions[fmt.format(plural_time_unit_1,
                                               singular_time_unit_2) +
                                    " ago"] = (True, False)
                        expressions["in " +
                                    fmt.format(plural_time_unit_1,
                                               singular_time_unit_2)] = (True,
                                                                         False)
                        expressions[fmt.format(singular_time_unit_1,
                                               plural_time_unit_2) +
                                    " ago"] = (False, True)
                        expressions["in " +
                                    fmt.format(singular_time_unit_1,
                                               plural_time_unit_2)] = (False,
                                                                       True)
                        expressions[fmt.format(singular_time_unit_1,
                                               singular_time_unit_2) +
                                    " ago"] = (False, False)
                        expressions["in " +
                                    fmt.format(singular_time_unit_1,
                                               singular_time_unit_2)] = (False,
                                                                         False)

                    for human_expression, quantity_tuple in expressions.items(
                    ):
                        shift_kwargs = {}
                        sign = 1 if human_expression.startswith("in ") else -1
                        if quantity_tuple[0]:
                            shift_kwargs[time_unit_1 + 's'] = shift_1 * sign
                        else:
                            shift_kwargs[time_unit_1 + 's'] = 1 * sign

                        if quantity_tuple[1]:
                            shift_kwargs[time_unit_2 + 's'] = shift_2 * sign
                        else:
                            shift_kwargs[time_unit_2 + 's'] = 1 * sign

                        now = XArrow.now()
                        dehumanized_instance_vanilla = Arrow.now().dehumanize(
                            human_expression)
                        dehumanized_instance_vanilla.microsecond = 0
                        dehumanized_static = XArrow.dehumanize(
                            human_expression)

                        now_shifted = now.shift(**shift_kwargs)
                        dehumanized_instance = now.dehumanize(human_expression)

                        try:
                            assert_arrows_soft_eq(dehumanized_instance,
                                                  now_shifted)
                            assert_arrows_soft_eq(dehumanized_static,
                                                  now_shifted)
                            assert_arrows_soft_eq(
                                dehumanized_instance,
                                dehumanized_instance_vanilla)
                            assert_arrows_soft_eq(
                                dehumanized_static,
                                dehumanized_instance_vanilla)
                        except AssertionError:
                            now = XArrow.now()
                            dehumanized_instance = now.dehumanize(
                                human_expression)
                            now_shifted = now.shift(**shift_kwargs)
                            assert_arrows_soft_eq(dehumanized_instance,
                                                  now_shifted)
                            dehumanized_static = XArrow.dehumanize(
                                human_expression)
                            assert_arrows_soft_eq(dehumanized_static,
                                                  now_shifted)
                            dehumanized_instance_vanilla = Arrow.now(
                            ).dehumanize(human_expression)
                            assert_arrows_soft_eq(
                                dehumanized_instance,
                                dehumanized_instance_vanilla)
                            assert_arrows_soft_eq(
                                dehumanized_static,
                                dehumanized_instance_vanilla)

                    # * 3 units
                    for time_unit_3 in TIME_UNITS:
                        if time_unit_3 == time_unit_1 or time_unit_3 == time_unit_2:
                            continue
                        if random() < 0.75:
                            continue
                        shift_3 = randint(2, 4)
                        singular_time_unit_3 = (f"a" if time_unit_3 != "hour"
                                                else "an") + f" {time_unit_3}"
                        plural_time_unit_3 = f"{shift_3} {time_unit_3}s"
                        expressions = {}
                        for fmt in [
                                "{0} and {1} and {2}",
                                "{0} and {1}, {2}",
                                "{0} and {1} {2}",
                                "{0}, {1}, {2}",
                                "{0}, {1} and {2}",
                                "{0}, {1} {2}",
                                "{0} {1} {2}",
                                "{0} {1}, {2}",
                                "{0} {1} and {2}",
                        ]:
                            for q1, q2, q3 in product(["plural", "singular"],
                                                      ["plural", "singular"],
                                                      ["plural", "singular"]):
                                past_human_expression = eval(
                                    f"fmt.format({q1}_time_unit_1, {q2}_time_unit_2, {q3}_time_unit_3) + ' ago'"
                                )
                                future_human_expression = eval(
                                    f"'in ' + fmt.format({q1}_time_unit_1, {q2}_time_unit_2, {q3}_time_unit_3)"
                                )
                                quantity_tuple = (q1 == "plural",
                                                  q2 == "plural",
                                                  q3 == "plural")
                                expressions[
                                    past_human_expression] = quantity_tuple
                                expressions[
                                    future_human_expression] = quantity_tuple
                        for human_expression, quantity_tuple in expressions.items(
                        ):
                            shift_kwargs = {}
                            sign = 1 if human_expression.startswith(
                                "in ") else -1
                            if quantity_tuple[0]:
                                shift_kwargs[time_unit_1 +
                                             's'] = shift_1 * sign
                            else:
                                shift_kwargs[time_unit_1 + 's'] = 1 * sign

                            if quantity_tuple[1]:
                                shift_kwargs[time_unit_2 +
                                             's'] = shift_2 * sign
                            else:
                                shift_kwargs[time_unit_2 + 's'] = 1 * sign

                            if quantity_tuple[2]:
                                shift_kwargs[time_unit_3 +
                                             's'] = shift_3 * sign
                            else:
                                shift_kwargs[time_unit_3 + 's'] = 1 * sign

                            now = XArrow.now()
                            dehumanized_instance_vanilla = Arrow.now(
                            ).dehumanize(human_expression)
                            dehumanized_static = XArrow.dehumanize(
                                human_expression)

                            now_shifted = now.shift(**shift_kwargs)
                            dehumanized_instance = now.dehumanize(
                                human_expression)

                            try:
                                assert_arrows_soft_eq(dehumanized_instance,
                                                      now_shifted)
                                assert_arrows_soft_eq(dehumanized_static,
                                                      now_shifted)
                                assert_arrows_soft_eq(
                                    dehumanized_instance,
                                    dehumanized_instance_vanilla)
                                assert_arrows_soft_eq(
                                    dehumanized_static,
                                    dehumanized_instance_vanilla)
                            except AssertionError:
                                now = XArrow.now()
                                dehumanized_instance = now.dehumanize(
                                    human_expression)
                                now_shifted = now.shift(**shift_kwargs)
                                assert_arrows_soft_eq(dehumanized_instance,
                                                      now_shifted)
                                dehumanized_static = XArrow.dehumanize(
                                    human_expression)
                                assert_arrows_soft_eq(dehumanized_static,
                                                      now_shifted)
                                dehumanized_instance_vanilla = Arrow.now(
                                ).dehumanize(human_expression)
                                assert_arrows_soft_eq(
                                    dehumanized_instance,
                                    dehumanized_instance_vanilla)
                                assert_arrows_soft_eq(
                                    dehumanized_static,
                                    dehumanized_instance_vanilla)
Example #32
0
            motd.append(
                f'{week_day_name} ({day_of_month_and_month_name}): {upcoming_motd_first_name}'
            )

        if len(motd) != 0:
            print("---")

            for m in motd:
                print(m)
    except:
        pass


def get_attendee_name(event: Event):
    return list(event.attendees)[0].common_name.split(' ')[0]


if __name__ == '__main__':
    try:
        req = requests.get(MotdConfig.MOTD_ICAL_URL,
                           timeout=MotdConfig.REQUEST_TIMEOUT)

        calendar = Calendar(req.text)
        timeline = list(
            calendar.timeline.start_after(Arrow.now().shift(days=-1)))

        print_current_motd(timeline)
        print_coming_motd(timeline)
    except:
        print(f'MotD: ? | templateImage={MotdIcons.MOTD_LOGO.base64_image}')