<commit_before>""" Convert an OpenTripPlanner json itinerary response into something that's more suitable for rendering via a webpage
"""
import re
import sys
import math
from decimal import *
import datetime
from datetime import timedelta
import simplejson as json

from ott.utils import object_utils
from ott.utils import json_utils

import logging
log = logging.getLogger(__file__)


class Error(object):
    def __init__(self, jsn, params=None):
        self.id  = jsn['id']
        self.msg = jsn['msg']


class DateInfo(object):
    def __init__(self, jsn):
        self.start_time_ms = jsn['startTime']
        self.end_time_ms = jsn['endTime']
        start = datetime.datetime.fromtimestamp(self.start_time_ms / 1000)
        end   = datetime.datetime.fromtimestamp(self.end_time_ms / 1000)

        self.date = "%d/%d/%d" % (start.month, start.day, start.year) # 29/2/2012
        self.pretty_date = start.strftime("%A, %B %d, %Y").replace(' 0',' ')    # "Monday, March 4, 2013"
        self.start_time  = start.strftime(" %I:%M%p").lower().replace(' 0','') # "3:40pm" -- note, keep pre-space
        self.end_time = end.strftime(" %I:%M%p").lower().replace(' 0','')    # "3:44pm" -- note, keep pre-space
        self.duration_ms = jsn['duration']
        self.duration = ms_to_minutes(self.duration_ms, is_pretty=True, show_hours=True)
        self.day   = start.day
        self.month = start.month
        self.year  = start.year


class DateInfoExtended(DateInfo):
    '''
    '''
    def __init__(self, jsn):
        super(DateInfoExtended, self).__init__(jsn)
        self.extended = True

        # step 1: get data
        walk = get_element(jsn, 'walkTime', 0)
        tran = get_element(jsn, 'transitTime', 0)
        wait = get_element(jsn, 'waitingTime', 0)
        tot  = walk + tran + wait

        # step 2: trip length
        h,m = seconds_to_hours_minutes(tot)
        self.total_time_hours = h
        self.total_time_mins = m
        self.duration_min = int(round(tot / 60))

        # step 3: transit info
        h,m = seconds_to_hours_minutes(tran)
        self.transit_time_hours = h
        self.transit_time_mins = m
        self.start_transit = "TODO"
        self.end_transit = "TODO"

        # step 4: bike / walk length
        self.bike_time_hours = None
        self.bike_time_mins = None
        self.walk_time_hours = None
        self.walk_time_mins = None
        if 'mode' in jsn and jsn['mode'] == 'BICYCLE':
            h,m = seconds_to_hours_minutes(walk)
            self.bike_time_hours = h
            self.bike_time_mins = m
        else:
            h,m = seconds_to_hours_minutes(walk)
            self.walk_time_hours = h
            self.walk_time_mins = m

        # step 5: wait time
        h,m = seconds_to_hours_minutes(wait)
        self.wait_time_hours = h
        self.wait_time_mins = m

        # step 5: drive time...unused as of now...
        self.drive_time_hours = None
        self.drive_time_mins = None
        self.text = self.get_text()


    def get_text(self):
        '''
        '''
        ret_val = ''
        tot =  hour_min_string(self.total_time_hours, self.total_time_mins)
        walk = hour_min_string(self.walk_time_hours, self.walk_time_mins)
        bike = hour_min_string(self.bike_time_hours, self.bike_time_mins)
        wait = hour_min_string(self.wait_time_hours, self.wait_time_mins)
        return ret_val


class Elevation(object):
    def __init__(self, steps):
        self.points   = None
        self.points_array = None
        self.distance = None
        self.start_ft = None
        self.end_ft   = None
        self.high_ft  = None
        self.low_ft   = None
        self.rise_ft  = None
        self.fall_ft  = None
        self.grade    = None

        self.distance = self.make_distance(steps)
        self.points_array, self.points = self.make_points(steps)
        self.grade = self.find_max_grade(steps)
        self.set_marks()

    @classmethod
    def make_distance(cls, steps):
        ''' loop through distance
        '''
        ret_val = None
        try:
            dist = 0
            for s in steps:
                dist += s['distance']
            ret_val = dist
        except Exception as ex:
            log.warning(ex)
        return ret_val

    @classmethod
    def make_point_string(cls, points, max_len=50):
        '''
        '''
        points_array = points

        if len(points) > (max_len * 1.15):
            # reduce the point array down to something around the size of max_len (or smaller)
            points_array = []

            # slice the array up into chunks
            # @see http://stackoverflow.com/questions/1335392/iteration-over-list-slices (thank you Nadia)
            slice_size = int(round(len(points) / max_len))
            if slice_size == 1:
                slice_size = 2
            list_of_slices = zip(*(iter(points),) * slice_size)

            # average up the slices
            for s in list_of_slices:
                avg = sum(s) / len(s)
                points_array.append(avg)

        points_string = ','.join(["{0:.2f}".format(p) for p in points_array])
        return points_string

    @classmethod
    def make_points(cls, steps):
        ''' parse leg for list of elevation points and distances
        '''
        points_array  = None
        points_string = None
        try:
            points = [] 
            for s in steps:
                for e in s['elevation']: 
                    elev = e['second']
                    dist = e['first']
                    points.append(round(elev, 2))
            if len(points) > 0:
                points_array  = points
                points_string = cls.make_point_string(points)
        except Exception as e:
            log.warning(e)
        return points_array, points_string

    @classmethod
    def find_max_grade(cls, steps):
        ''' parse leg for list of elevation points and distances
        '''
        r = {'up':0, 'down':0, 'ue':0, 'ud':0, 'de':0, 'dd':0}
        ret_val = r
        try:
            for s in steps:
                first = True
                going_up = False
                for e in s['elevation']: 
                    dist = e['first']
                    elev = e['second']

                    if first:
                        first = False
                        r['ue'] = elev
                        r['ud'] = dist
                        r['de'] = elev
                        r['dd'] = dist
                    else:
                        # going up
                        if elev > r['lue']:
                            # set up vals
                            r['lue'] = elev
                            r['lud'] = dist

                            # set down vals
                            going_up = True
                        elif elev < r['lue']:
                            last_elev = elev

                    print elev
        except Exception, e:
            log.warning(e)<commit_msg>removed print statement that was outputting elevations each a trip was planned<commit_after>""" Convert an OpenTripPlanner json itinerary response into something that's more suitable for rendering via a webpage
"""
import re
import sys
import math
from decimal import *
import datetime
from datetime import timedelta
import simplejson as json

from ott.utils import object_utils
from ott.utils import json_utils

import logging
log = logging.getLogger(__file__)


class Error(object):
    def __init__(self, jsn, params=None):
        self.id  = jsn['id']
        self.msg = jsn['msg']


class DateInfo(object):
    def __init__(self, jsn):
        self.start_time_ms = jsn['startTime']
        self.end_time_ms = jsn['endTime']
        start = datetime.datetime.fromtimestamp(self.start_time_ms / 1000)
        end   = datetime.datetime.fromtimestamp(self.end_time_ms / 1000)

        self.date = "%d/%d/%d" % (start.month, start.day, start.year) # 29/2/2012
        self.pretty_date = start.strftime("%A, %B %d, %Y").replace(' 0',' ')    # "Monday, March 4, 2013"
        self.start_time  = start.strftime(" %I:%M%p").lower().replace(' 0','') # "3:40pm" -- note, keep pre-space
        self.end_time = end.strftime(" %I:%M%p").lower().replace(' 0','')    # "3:44pm" -- note, keep pre-space
        self.duration_ms = jsn['duration']
        self.duration = ms_to_minutes(self.duration_ms, is_pretty=True, show_hours=True)
        self.day   = start.day
        self.month = start.month
        self.year  = start.year


class DateInfoExtended(DateInfo):
    '''
    '''
    def __init__(self, jsn):
        super(DateInfoExtended, self).__init__(jsn)
        self.extended = True

        # step 1: get data
        walk = get_element(jsn, 'walkTime', 0)
        tran = get_element(jsn, 'transitTime', 0)
        wait = get_element(jsn, 'waitingTime', 0)
        tot  = walk + tran + wait

        # step 2: trip length
        h,m = seconds_to_hours_minutes(tot)
        self.total_time_hours = h
        self.total_time_mins = m
        self.duration_min = int(round(tot / 60))

        # step 3: transit info
        h,m = seconds_to_hours_minutes(tran)
        self.transit_time_hours = h
        self.transit_time_mins = m
        self.start_transit = "TODO"
        self.end_transit = "TODO"

        # step 4: bike / walk length
        self.bike_time_hours = None
        self.bike_time_mins = None
        self.walk_time_hours = None
        self.walk_time_mins = None
        if 'mode' in jsn and jsn['mode'] == 'BICYCLE':
            h,m = seconds_to_hours_minutes(walk)
            self.bike_time_hours = h
            self.bike_time_mins = m
        else:
            h,m = seconds_to_hours_minutes(walk)
            self.walk_time_hours = h
            self.walk_time_mins = m

        # step 5: wait time
        h,m = seconds_to_hours_minutes(wait)
        self.wait_time_hours = h
        self.wait_time_mins = m

        # step 5: drive time...unused as of now...
        self.drive_time_hours = None
        self.drive_time_mins = None
        self.text = self.get_text()


    def get_text(self):
        '''
        '''
        ret_val = ''
        tot =  hour_min_string(self.total_time_hours, self.total_time_mins)
        walk = hour_min_string(self.walk_time_hours, self.walk_time_mins)
        bike = hour_min_string(self.bike_time_hours, self.bike_time_mins)
        wait = hour_min_string(self.wait_time_hours, self.wait_time_mins)
        return ret_val


class Elevation(object):
    def __init__(self, steps):
        self.points   = None
        self.points_array = None
        self.distance = None
        self.start_ft = None
        self.end_ft   = None
        self.high_ft  = None
        self.low_ft   = None
        self.rise_ft  = None
        self.fall_ft  = None
        self.grade    = None

        self.distance = self.make_distance(steps)
        self.points_array, self.points = self.make_points(steps)
        self.grade = self.find_max_grade(steps)
        self.set_marks()

    @classmethod
    def make_distance(cls, steps):
        ''' loop through distance
        '''
        ret_val = None
        try:
            dist = 0
            for s in steps:
                dist += s['distance']
            ret_val = dist
        except Exception as ex:
            log.warning(ex)
        return ret_val

    @classmethod
    def make_point_string(cls, points, max_len=50):
        '''
        '''
        points_array = points

        if len(points) > (max_len * 1.15):
            # reduce the point array down to something around the size of max_len (or smaller)
            points_array = []

            # slice the array up into chunks
            # @see http://stackoverflow.com/questions/1335392/iteration-over-list-slices (thank you Nadia)
            slice_size = int(round(len(points) / max_len))
            if slice_size == 1:
                slice_size = 2
            list_of_slices = zip(*(iter(points),) * slice_size)

            # average up the slices
            for s in list_of_slices:
                avg = sum(s) / len(s)
                points_array.append(avg)

        points_string = ','.join(["{0:.2f}".format(p) for p in points_array])
        return points_string

    @classmethod
    def make_points(cls, steps):
        ''' parse leg for list of elevation points and distances
        '''
        points_array  = None
        points_string = None
        try:
            points = [] 
            for s in steps:
                for e in s['elevation']: 
                    elev = e['second']
                    dist = e['first']
                    points.append(round(elev, 2))
            if len(points) > 0:
                points_array  = points
                points_string = cls.make_point_string(points)
        except Exception as e:
            log.warning(e)
        return points_array, points_string

    @classmethod
    def find_max_grade(cls, steps):
        ''' parse leg for list of elevation points and distances
        '''
        r = {'up':0, 'down':0, 'ue':0, 'ud':0, 'de':0, 'dd':0}
        ret_val = r
        try:
            for s in steps:
                first = True
                going_up = False
                for e in s['elevation']: 
                    dist = e['first']
                    elev = e['second']

                    if first:
                        first = False
                        r['ue'] = elev
                        r['ud'] = dist
                        r['de'] = elev
                        r['dd'] = dist
                    else:
                        # going up
                        if elev > r['lue']:
                            # set up vals
                            r['lue'] = elev
                            r['lud'] = dist

                            # set down vals
                            going_up = True
                        elif elev < r['lue']:
                            last_elev = elev
        except Exception, e:
            log.warning(e)
{'fraction_non_alphanumeric': 0.10212947795741044, 'fraction_numerical': 0.009258599814828003, 'mean_word_length': 1.6630001896453632, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '215501', 'n_tokens_mistral': 4434, 'n_tokens_neox': 4151, 'n_words': 1012}