Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
summary_polyline = Attribute(str, (SUMMARY, DETAILED)) #: Google polyline encoding for summary shape
class Split(BaseEntity):
"""
A split -- may be metric or standard units (which has no bearing
on the units used in this object, just the binning of values).
"""
distance = Attribute(float, units=uh.meters) #: Distance for this split
elapsed_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of elapsed time for split
elevation_difference = Attribute(float, units=uh.meters) #: Elevation difference for split
moving_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of moving time for split
average_heartrate = Attribute(float) #: Average HR for split
split = Attribute(int) #: Which split number
pace_zone = Attribute(int) #: (undocumented)
average_speed = Attribute(float, units=uh.meters_per_second)
def __repr__(self):
return ''.format(self.split, self.distance, self.elapsed_time)
class SegmentExplorerResult(LoadableEntity):
"""
Represents a segment result from the segment explorer feature.
(These are not full segment objects, but the segment object can be fetched
via the 'segment' property of this object.)
"""
_segment = None
id = Attribute(int) #: ID of the segment.
name = Attribute(six.text_type) #: Name of the segment
climb_category = Attribute(int) #: Climb category for the segment (0 is higher)
average_speed = Attribute(float, (SUMMARY, DETAILED,), units=uh.meters_per_second) #: Average speed for lap
max_speed = Attribute(float, (SUMMARY, DETAILED,), units=uh.meters_per_second) #: Max speed for lap
average_cadence = Attribute(float, (SUMMARY, DETAILED,)) #: Average cadence for lap
average_watts = Attribute(float, (SUMMARY, DETAILED,)) #: Average watts for lap
average_heartrate = Attribute(float, (SUMMARY, DETAILED,)) #: Average heartrate for lap
max_heartrate = Attribute(float, (SUMMARY, DETAILED,)) #: Max heartrate for lap
lap_index = Attribute(int, (SUMMARY, DETAILED)) #: Index of lap
device_watts = Attribute(bool, (SUMMARY, DETAILED)) # true if the watts are from a power meter, false if estimated
pace_zone = Attribute(int, (SUMMARY, DETAILED)) #: (undocumented)
split = Attribute(int, (SUMMARY, DETAILED)) #: Split number
class Map(IdentifiableEntity):
id = Attribute(six.text_type, (SUMMARY, DETAILED)) #: Alpha-numeric identifier
polyline = Attribute(str, (SUMMARY, DETAILED)) #: Google polyline encoding
summary_polyline = Attribute(str, (SUMMARY, DETAILED)) #: Google polyline encoding for summary shape
class Split(BaseEntity):
"""
A split -- may be metric or standard units (which has no bearing
on the units used in this object, just the binning of values).
"""
distance = Attribute(float, units=uh.meters) #: Distance for this split
elapsed_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of elapsed time for split
elevation_difference = Attribute(float, units=uh.meters) #: Elevation difference for split
moving_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of moving time for split
average_heartrate = Attribute(float) #: Average HR for split
split = Attribute(int) #: Which split number
pace_zone = Attribute(int) #: (undocumented)
average_speed = Attribute(float, units=uh.meters_per_second)
# The existing access_token is expired
# Attempt to refresh the token
try:
new_access_info = self.cli.refresh_access_token(
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET,
refresh_token=access_info.get("refresh_token"))
self.access_token = json.dumps(new_access_info)
try:
session.commit()
except Exception:
log.exception("postgres error")
self.cli = stravalib.Client(
access_token=new_access_info.get("access_token"),
rate_limiter=(lambda x=None: None)
)
except Exception:
log.exception("%s token refresh fail", self)
self.cli = None
else:
elapsed = round(time.time() - start, 2)
log.debug("%s token refresh elapsed=%s", self, elapsed)
return self.cli
if not os.path.isfile(gpxfile):
logger.warning("No file found for " + gpxfile + "!")
return False
logger.debug("Uploading " + gpxfile)
try:
upload = client.upload_activity(
activity_file = open(gpxfile,'r'),
data_type = 'gpx',
private = False,
description = notes,
activity_type = strava_activity_type
)
except exc.ActivityUploadFailed as err:
errStr = str(err)
# deal with duplicate type of error, if duplicate then continue with next file, else stop
if errStr.find('duplicate of activity'):
archive_file(gpxfile)
logger.debug("Duplicate File " + gpxfile)
return True
else:
logger.error("Another ActivityUploadFailed error: {}".format(err))
exit(1)
except ConnectionError as err:
logger.error("No Internet connection: {}".format(err))
exit(1)
logger.info("Upload succeeded.\nWaiting for response...")
uh.timedelta_to_seconds(timedelta(seconds=int(rain_res["moving_time"]))) / 3600
)
q = text(
"""
select count(*) as num_rides, coalesce(sum(R.moving_time),0) as moving_time
from rides R
join ride_weather W on W.ride_id = R.id
where W.ride_snow = 1
;
"""
)
snow_res = meta.scoped_session().execute(q).fetchone() # @UndefinedVariable
snow_hours = (
uh.timedelta_to_seconds(timedelta(seconds=int(snow_res["moving_time"]))) / 3600
)
# Grab some recent photos
photos = (
meta.scoped_session()
.query(RidePhoto)
.join(Ride)
.order_by(Ride.start_date.desc())
.limit(11)
)
return render_template(
"index.html",
team_count=len(config.COMPETITION_TEAMS),
contestant_count=contestant_count,
total_rides=total_rides,
import BaseHTTPServer
import urlparse
import webbrowser
import pandas as pd
import datetime
#Global Variables - put your data in the file 'client.secret' and separate the fields with a comma!
client_id, secret = open('client.secret').read().strip().split(',')
port = 5000
url = 'http://localhost:%d/authorized' % port
allDone = False
types = ['time', 'distance', 'latlng', 'altitude', 'velocity_smooth', 'moving', 'grade_smooth', 'temp']
limit = 10
#Create the strava client, and open the web browser for authentication
client = stravalib.client.Client()
authorize_url = client.authorization_url(client_id=client_id, redirect_uri=url)
print 'Opening: %s' % authorize_url
webbrowser.open(authorize_url)
#Define the web functions to call from the strava API
def UseCode(code):
#Retrieve the login code from the Strava server
access_token = client.exchange_code_for_token(client_id=client_id,
client_secret=secret, code=code)
# Now store that access token somewhere (for now, it's just a local variable)
client.access_token = access_token
athlete = client.get_athlete()
print("For %(id)s, I now have an access token %(token)s" %
{'id': athlete.id, 'token': access_token})
return client
def strava_authorized():
code = request.args.get('code') # or whatever your framework does
client = stravalib.client.Client()
access_token = client.exchange_code_for_token(client_id=app.config['STRAVA_CLIENT_ID'], client_secret=app.config['STRAVA_CLIENT_SECRET'], code=code)
current_user.preferences['strava'] = UserPreference('strava', access_token)
db.session.commit()
flash("Access to Strava API granted")
return redirect(url_for('move_import'))
streams_json = self.get_cached_streams_json(ride) if use_cache else None
if streams_json is None:
if options.only_cache:
self.logger.info("[CACHE-MISS] Skipping ride {} since there is no cached stream.".format(ride))
continue
self.logger.info("[CACHE-MISS] Fetching streams for {!r}".format(ride))
# We do this manually, so that we can cache the JSON for later use.
streams_json = client.protocol.get(
'/activities/{id}/streams/{types}'.format(id=ride.id, types='latlng,time,altitude'),
resolution='low'
)
streams = [stravamodel.Stream.deserialize(stream_struct, bind_client=client) for stream_struct in streams_json]
try:
self.logger.info("Caching streams for {!r}".format(ride))
self.cache_stream(ride, streams_json)
except:
log.error("Error caching streams for activity {} (ignoring)".format(ride),
exc_info=self.logger.isEnabledFor(logging.DEBUG))
else:
streams = [stravamodel.Stream.deserialize(stream_struct, bind_client=client) for stream_struct in streams_json]
self.logger.info("[CACHE-HIT] Using cached streams detail for {!r}".format(ride))
data.write_ride_streams(streams, ride)
meta.session_factory().commit()
except:
soup = BeautifulSoup(r.text)
authenticity_token = soup.find('input', attrs=dict(name="authenticity_token"))['value']
params = {'_method': 'post',
'authenticity_token': authenticity_token}
files = {'files[]': fileobj}
r = self.rsession.post('http://app.strava.com/upload/files', data=params, files=files, cookies=self.cookies)
r.raise_for_status()
matches = re.search(r'var uploadingIds\s*=\s*\[([\d,]+)\];', r.text)
if not matches:
self.log.debug(r.text)
raise exc.Fault("Unable to locate upload IDs in reponse (enable debug logging to see response html page)")
upload_ids = [int(u_id.strip()) for u_id in matches.group(1).split(',')]
return upload_ids
average_watts = Attribute(float, (SUMMARY, DETAILED,)) #: Average watts for lap
average_heartrate = Attribute(float, (SUMMARY, DETAILED,)) #: Average heartrate for lap
max_heartrate = Attribute(float, (SUMMARY, DETAILED,)) #: Max heartrate for lap
lap_index = Attribute(int, (SUMMARY, DETAILED)) #: Index of lap
device_watts = Attribute(bool, (SUMMARY, DETAILED)) # true if the watts are from a power meter, false if estimated
pace_zone = Attribute(int, (SUMMARY, DETAILED)) #: (undocumented)
split = Attribute(int, (SUMMARY, DETAILED)) #: Split number
class Map(IdentifiableEntity):
id = Attribute(six.text_type, (SUMMARY, DETAILED)) #: Alpha-numeric identifier
polyline = Attribute(str, (SUMMARY, DETAILED)) #: Google polyline encoding
summary_polyline = Attribute(str, (SUMMARY, DETAILED)) #: Google polyline encoding for summary shape
class Split(BaseEntity):
"""
A split -- may be metric or standard units (which has no bearing
on the units used in this object, just the binning of values).
"""
distance = Attribute(float, units=uh.meters) #: Distance for this split
elapsed_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of elapsed time for split
elevation_difference = Attribute(float, units=uh.meters) #: Elevation difference for split
moving_time = TimeIntervalAttribute() #: :class:`datetime.timedelta` of moving time for split
average_heartrate = Attribute(float) #: Average HR for split
split = Attribute(int) #: Which split number
pace_zone = Attribute(int) #: (undocumented)
average_speed = Attribute(float, units=uh.meters_per_second)
def __repr__(self):
return ''.format(self.split, self.distance, self.elapsed_time)