Python maya.parse() Examples

The following are 26 code examples of maya.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module maya , or try the search function .
Example #1
Source File: test_maya.py    From maya with MIT License 6 votes vote down vote up
def test_getting_datetime_for_local_timezone(monkeypatch):
    @property
    def mock_local_tz(self):
        class StaticTzInfo(object):
            zone = "Europe/Zurich"

            def __repr__(self):
                return "<StaticTzInfo 'Europe/Zurich'>"

        return StaticTzInfo()

    monkeypatch.setattr(maya.MayaDT, "_local_tz", mock_local_tz)

    d = maya.parse("1994-02-21T12:00:00+05:30")

    dt = pytz.timezone("Europe/Zurich").localize(Datetime(1994, 2, 21, 7, 30))

    assert d.local_datetime() == dt 
Example #2
Source File: interval.py    From marge-bot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def from_human(cls, string):
        from_, to_ = string.split('-')

        def parse_part(part):
            part = part.replace('@', ' ')
            parts = part.split()
            weekday = parts[0]
            time = parts[1]
            timezone = parts[2] if len(parts) > 2 else 'UTC'
            weekday = find_weekday(weekday)
            time = maya.parse(time, timezone=timezone).datetime().time()
            return weekday, time

        from_weekday, from_time = parse_part(from_)
        to_weekday, to_time = parse_part(to_)
        return cls(from_weekday, from_time, to_weekday, to_time) 
Example #3
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def _request_strava_authorize(client_id, port):
    params_oauth = {
        "client_id": client_id,
        "response_type": "code",
        "redirect_uri": f"http://localhost:{port}/authorization_successful",
        "scope": "read,profile:read_all,activity:read",
        "state": 'https://github.com/sladkovm/strava-http',
        "approval_prompt": "force"
    }
    values_url = urllib.parse.urlencode(params_oauth)
    base_url = 'https://www.strava.com/oauth/authorize'
    rv = base_url + '?' + values_url
    webbrowser.get().open(rv)
    return None 
Example #4
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __validate_timestamp(self):
        try:
            maya.parse(self.timestamp, day_first=True, year_first=False)
        except Exception:
            raise GraphQLError(
                'The timestamp you provided is not within the format: "dd/mm/yyyy hh:mm"'
            ) 
Example #5
Source File: models.py    From flask-graphql-neo4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def as_dict(self):
        return {
            '_id': self.__primaryvalue__,
            'total_amount': self.total_amount,
            'timestamp': maya.parse(self.timestamp)
        } 
Example #6
Source File: test_maya.py    From maya with MIT License 5 votes vote down vote up
def test_parse(string, kwds, expected):
    d = maya.parse(string, **kwds)
    assert format(d) == expected 
Example #7
Source File: test_maya.py    From maya with MIT License 5 votes vote down vote up
def test_machine_parse():
    r1 = maya.parse("August 14, 2015")
    assert r1.day == 14
    r2 = maya.parse("August 15, 2015")
    assert r2.day == 15 
Example #8
Source File: test_maya.py    From maya with MIT License 5 votes vote down vote up
def test_long_count(string, expected):
    r = maya.parse(string).long_count()
    d = maya.MayaDT.from_long_count(r)
    assert r == expected
    assert r == d.long_count() 
Example #9
Source File: test_maya.py    From maya with MIT License 5 votes vote down vote up
def test_iso8601(string, expected):
    r = maya.parse(string).iso8601()
    d = maya.MayaDT.from_iso8601(r)
    assert r == expected
    assert r == d.iso8601() 
Example #10
Source File: test_maya.py    From maya with MIT License 5 votes vote down vote up
def test_rfc2822(string, expected):
    r = maya.parse(string).rfc2822()
    d = maya.MayaDT.from_rfc2822(r)
    assert r == expected
    assert r == d.rfc2822() 
Example #11
Source File: test_maya_interval.py    From maya with MIT License 5 votes vote down vote up
def test_intervals(start_string, end_string, interval, expected_count):
    start = maya.parse(start_string)
    end = maya.parse(end_string)
    assert len(list(maya.intervals(start, end, interval))) == expected_count 
Example #12
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def date_to_epoch(date):
    """Convert a date to epoch representation"""
    rv = None
    if isinstance(date, int):
        rv = date
    if isinstance(date, datetime.datetime):
        _ = maya.parse(date)
        rv = _.epoch
    if isinstance(date, str):
        _ = maya.when(date)
        rv = _.epoch
    if rv is None:
        raise TypeError('date must be epoch int, datetime obj or the string')
    return rv 
Example #13
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def convert_datetime_to_iso8601(d):
    for k, v in d.items():
        if isinstance(v, dict):
            convert_datetime_to_iso8601(v)
        elif isinstance(v, list):
            for i in v:
                if isinstance(i, dict):
                    convert_datetime_to_iso8601(i)
        else:
            if isinstance(v, datetime.datetime):
                d[k] = maya.parse(v).iso8601()
    return d 
Example #14
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def run_server_and_wait_for_token(port, client_id, client_secret):
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', port))
        s.listen()
        conn, addr = s.accept()

        request_bytes = b''
        with conn:
            while True:
                chunk = conn.recv(512)
                request_bytes += chunk

                if request_bytes.endswith(b'\r\n\r\n'):
                    break
            conn.sendall(b'HTTP/1.1 200 OK\r\n\r\nsuccess\r\n')

        request = request_bytes.decode('utf-8')
        status_line = request.split('\n', 1)[0]
        
        method, raw_url, protocol_version = status_line.split(' ')
        
        url = urllib.parse.urlparse(raw_url)
        query_string = url.query
        query_params = urllib.parse.parse_qs(query_string, keep_blank_values=True)

        if url.path == "/authorization_successful":
            code = query_params.get('code')[0]
            logger.debug(f"code: {code}")
            params = {
                "client_id": client_id,
                "client_secret": client_secret,
                "code": code,
                "grant_type": "authorization_code"
            }
            r = requests.post("https://www.strava.com/oauth/token", params)
            data = r.json()
            logger.debug(f"Authorized athlete: {data.get('access_token', 'Oeps something went wrong!')}")
        else:
            data = url.path.encode()
        
        return data 
Example #15
Source File: stravaio.py    From stravaio with MIT License 5 votes vote down vote up
def get_logged_in_athlete_activities(self, after=0, list_activities=None):
        """List all activities after a given date
        
        Parameters
        ----------
        after: int, str or datetime object
            If integer, the time since epoch is assumed
            If str, the maya.parse() compatible date string is expected e.g. iso8601 or 2018-01-01 or 20180101
            If datetime, the datetime object is expected

        Returns
        -------
        list_activities: list
            List of SummaryActivity objects
        """
        if list_activities is None:
            list_activities = []
        after = date_to_epoch(after)
        _fetched = self.activities_api.get_logged_in_athlete_activities(after=after)
        if len(_fetched) > 0:
            print(f"Fetched {len(_fetched)}, the latests is on {_fetched[-1].start_date}")
            list_activities.extend(_fetched)
            if len(_fetched) == 30:
                last_after = list_activities[-1].start_date
                return self.get_logged_in_athlete_activities(after=last_after, list_activities=list_activities)
        else:
            print("empty list")
        
        return list_activities 
Example #16
Source File: topic.py    From contextualise with MIT License 5 votes vote down vote up
def view_names(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        current_app.logger.warning(
            f"Topic map not found: user identifier: [{current_user.id}], topic map identifier: [{map_identifier}]"
        )
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    if topic is None:
        current_app.logger.warning(
            f"Topic not found: user identifier: [{current_user.id}], topic map identifier: [{map_identifier}], topic identifier: [{topic_identifier}]"
        )
        abort(404)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template("topic/view_names.html", topic_map=topic_map, topic=topic, creation_date=creation_date,) 
Example #17
Source File: three_d.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    file_occurrences = topic_store.get_topic_occurrences(
        map_identifier, topic_identifier, "3d-scene", resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    files = []
    for file_occurrence in file_occurrences:
        files.append(
            {
                "identifier": file_occurrence.identifier,
                "title": file_occurrence.get_attribute_by_name("title").value,
                "scope": file_occurrence.scope,
                "url": file_occurrence.resource_ref,
            }
        )

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "three_d/index.html", topic_map=topic_map, topic=topic, files=files, creation_date=creation_date,
    ) 
Example #18
Source File: association.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    associations = topic_store.get_topic_associations(map_identifier, topic_identifier)

    # occurrences_stats = topic_store.get_topic_occurrences_statistics(map_identifier, topic_identifier)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "association/index.html",
        topic_map=topic_map,
        topic=topic,
        associations=associations,
        creation_date=creation_date,
    ) 
Example #19
Source File: file.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    file_occurrences = topic_store.get_topic_occurrences(
        map_identifier, topic_identifier, "file", resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    files = []
    for file_occurrence in file_occurrences:
        files.append(
            {
                "identifier": file_occurrence.identifier,
                "title": file_occurrence.get_attribute_by_name("title").value,
                "scope": file_occurrence.scope,
                "url": file_occurrence.resource_ref,
            }
        )

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "file/index.html", topic_map=topic_map, topic=topic, files=files, creation_date=creation_date,
    ) 
Example #20
Source File: visualisation.py    From contextualise with MIT License 5 votes vote down vote up
def map(map_identifier, topic_identifier):  # TODO: Shadows built-in name 'map'. Rename?
    topic_store = get_topic_store()

    collaboration_mode = None
    if current_user.is_authenticated:  # User is logged in
        is_map_owner = topic_store.is_topic_map_owner(map_identifier, current_user.id)
        if is_map_owner:
            topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
        else:
            topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        collaboration_mode = topic_store.get_collaboration_mode(map_identifier, current_user.id)
        # The map is private and doesn't belong to the user who is trying to
        # access it
        if not topic_map.published and not is_map_owner:
            if not collaboration_mode:  # The user is not collaborating on the map
                abort(403)
    else:  # User is not logged in
        topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        if not topic_map.published:  # User is not logged in and the map is not published
            abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "visualisation/map.html",
        topic_map=topic_map,
        topic=topic,
        creation_date=creation_date,
        collaboration_mode=topic_map.collaboration_mode,
    ) 
Example #21
Source File: visualisation.py    From contextualise with MIT License 5 votes vote down vote up
def network(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    collaboration_mode = None
    if current_user.is_authenticated:  # User is logged in
        is_map_owner = topic_store.is_topic_map_owner(map_identifier, current_user.id)
        if is_map_owner:
            topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
        else:
            topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        collaboration_mode = topic_store.get_collaboration_mode(map_identifier, current_user.id)
        # The map is private and doesn't belong to the user who is trying to
        # access it
        if not topic_map.published and not is_map_owner:
            if not collaboration_mode:  # The user is not collaborating on the map
                abort(403)
    else:  # User is not logged in
        topic_map = topic_store.get_topic_map(map_identifier)
        if topic_map is None:
            abort(404)
        if not topic_map.published:  # User is not logged in and the map is not published
            abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "visualisation/network.html",
        topic_map=topic_map,
        topic=topic,
        creation_date=creation_date,
        collaboration_mode=collaboration_mode,
    ) 
Example #22
Source File: link.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    link_occurrences = topic_store.get_topic_occurrences(
        map_identifier, topic_identifier, "url", resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    links = []
    for link_occurrence in link_occurrences:
        links.append(
            {
                "identifier": link_occurrence.identifier,
                "title": link_occurrence.get_attribute_by_name("title").value,
                "scope": link_occurrence.scope,
                "url": link_occurrence.resource_ref,
            }
        )

    # occurrences_stats = topic_store.get_topic_occurrences_statistics(map_identifier, topic_identifier)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "link/index.html", topic_map=topic_map, topic=topic, links=links, creation_date=creation_date,
    ) 
Example #23
Source File: video.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    video_occurrences = topic_store.get_topic_occurrences(
        map_identifier, topic_identifier, "video", resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    videos = []
    for video_occurrence in video_occurrences:
        videos.append(
            {
                "identifier": video_occurrence.identifier,
                "title": video_occurrence.get_attribute_by_name("title").value,
                "scope": video_occurrence.scope,
                "url": video_occurrence.resource_ref,
            }
        )

    # occurrences_stats = topic_store.get_topic_occurrences_statistics(map_identifier, topic_identifier)

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "video/index.html", topic_map=topic_map, topic=topic, videos=videos, creation_date=creation_date,
    ) 
Example #24
Source File: image.py    From contextualise with MIT License 5 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    image_occurrences = topic_store.get_topic_occurrences(
        map_identifier, topic_identifier, "image", resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )

    images = []
    for image_occurrence in image_occurrences:
        images.append(
            {
                "identifier": image_occurrence.identifier,
                "title": image_occurrence.get_attribute_by_name("title").value,
                "scope": image_occurrence.scope,
                "url": image_occurrence.resource_ref,
            }
        )

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    return render_template(
        "image/index.html", topic_map=topic_map, topic=topic, images=images, creation_date=creation_date,
    ) 
Example #25
Source File: test_interval.py    From marge-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def date(spec):
    return maya.parse(spec).datetime() 
Example #26
Source File: attribute.py    From contextualise with MIT License 4 votes vote down vote up
def index(map_identifier, topic_identifier):
    topic_store = get_topic_store()

    if "admin" not in current_user.roles:
        abort(403)
    topic_map = topic_store.get_topic_map(map_identifier, current_user.id)
    if topic_map is None:
        abort(404)
    # If the map doesn't belong to the user and they don't have the right
    # collaboration mode on the map, then abort
    if not topic_map.owner and topic_map.collaboration_mode is not CollaborationMode.EDIT:
        abort(403)

    topic = topic_store.get_topic(
        map_identifier, topic_identifier, resolve_attributes=RetrievalMode.RESOLVE_ATTRIBUTES,
    )
    if topic is None:
        abort(404)

    attributes = []
    entity_attributes = topic_store.get_attributes(map_identifier, topic_identifier)

    for entity_attribute in entity_attributes:
        attributes.append(
            {
                "identifier": entity_attribute.identifier,
                "name": entity_attribute.name,
                "value": entity_attribute.value,
                "type": str(entity_attribute.data_type).lower(),
                "scope": entity_attribute.scope,
            }
        )

    creation_date_attribute = topic.get_attribute_by_name("creation-timestamp")
    creation_date = maya.parse(creation_date_attribute.value) if creation_date_attribute else "Undefined"

    entity_type = "topic"
    return_url = "topic.view"

    return render_template(
        "attribute/index.html",
        topic_map=topic_map,
        topic=topic,
        entity_type=entity_type,
        return_url=return_url,
        attributes=attributes,
        creation_date=creation_date,
    )