text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
async def _grab_connection(self, url): ''' The connection pool handler. Returns a connection to the caller. If there are no connections ready, and as many connections checked out as there are available total, we yield control to the event loop. If there is a connection ready or space to create a new one, we pop/create it, register it as checked out, and return it. Args: url (str): breaks the url down and uses the top level location info to see if we have any connections to the location already lying around. ''' scheme, host, _, _, _, _ = urlparse(url) host_loc = urlunparse((scheme, host, '', '', '', '')) sock = self._checkout_connection(host_loc) if sock is None: sock = await self._make_connection(host_loc) return sock
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def json(self, **kwargs): ''' If the response's body is valid json, we load it as a python dict and return it. ''' body = self._decompress(self.encoding) return _json.loads(body, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def raise_for_status(self): ''' Raise BadStatus if one occurred. ''' if 400 <= self.status_code < 500: raise BadStatus('{} Client Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code) elif 500 <= self.status_code < 600: raise BadStatus('{} Server Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def recent_photos(request): ''' returns all the images from the data base ''' imgs = [] for obj in Image_File.objects.filter(is_image=True).order_by("-date_created"): upurl = "/" + obj.upload.url thumburl = "" if obj.thumbnail: thumburl = "/" + obj.thumbnail.url imgs.append({'src': upurl, 'thumb': thumburl, 'is_image': True}) return render_to_response('dashboard/browse.html', {'files': imgs})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marshal(self, v): """ Turn this value into API format. Do a reverse dictionary lookup on choices to find the original value. If there are no keys or too many keys for now we raise a NotImplementedError as marshal is not used anywhere currently. In the future we will want to fail gracefully. """
if v: orig = [i for i in self.choices if self.choices[i] == v] if len(orig) == 1: return orig[0] elif len(orig) == 0: # No such choice raise NotImplementedError("No such reverse choice {0} for field {1}.".format(v, self)) else: # Too many choices. We could return one possible choice (e.g. orig[0]). raise NotImplementedError("Too many reverse choices {0} for value {1} for field {2}".format(orig, v, self))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmarshal(self, v): """ Convert the value from Strava API format to useful python representation. If the value does not appear in the choices attribute we log an error rather than raising an exception as this may be caused by a change to the API upstream so we want to fail gracefully. """
try: return self.choices[v] except KeyError: self.log.warning("No such choice {0} for field {1}.".format(v, self)) # Just return the value from the API return v
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmarshal(self, value, bind_client=None): """ Cast the specified value to the entity type. """
#self.log.debug("Unmarshall {0!r}: {1!r}".format(self, value)) if not isinstance(value, self.type): o = self.type() if bind_client is not None and hasattr(o.__class__, 'bind_client'): o.bind_client = bind_client if isinstance(value, dict): for (k, v) in value.items(): if not hasattr(o.__class__, k): self.log.warning("Unable to set attribute {0} on entity {1!r}".format(k, o)) else: #self.log.debug("Setting attribute {0} on entity {1!r}".format(k, o)) setattr(o, k, v) value = o else: raise Exception("Unable to unmarshall object {0!r}".format(value)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def marshal(self, values): """ Turn a list of entities into a list of dictionaries. :param values: The entities to serialize. :type values: List[stravalib.model.BaseEntity] :return: List of dictionaries of attributes :rtype: List[Dict[str, Any]] """
if values is not None: return [super(EntityCollection, self).marshal(v) for v in values]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unmarshal(self, values, bind_client=None): """ Cast the list. """
if values is not None: return [super(EntityCollection, self).unmarshal(v, bind_client=bind_client) for v in values]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorization_url(self, client_id, redirect_uri, approval_prompt='auto', scope=None, state=None): """ Get the URL needed to authorize your application to access a Strava user's information. :param client_id: The numeric developer client id. :type client_id: int :param redirect_uri: The URL that Strava will redirect to after successful (or failed) authorization. :type redirect_uri: str :param approval_prompt: Whether to prompt for approval even if approval already granted to app. Choices are 'auto' or 'force'. (Default is 'auto') :type approval_prompt: str :param scope: The access scope required. Omit to imply "public". Valid values are 'read', 'read_all', 'profile:read_all', 'profile:write', 'profile:read_all', 'activity:read_all', 'activity:write' :type scope: str :param state: An arbitrary variable that will be returned to your application in the redirect URI. :type state: str :return: The URL to use for authorization link. :rtype: str """
return self.protocol.authorization_url(client_id=client_id, redirect_uri=redirect_uri, approval_prompt=approval_prompt, scope=scope, state=state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activities(self, before=None, after=None, limit=None): """ Get activities for authenticated user sorted by newest first. http://strava.github.io/api/v3/activities/ :param before: Result will start with activities whose start date is before specified date. (UTC) :type before: datetime.datetime or str or None :param after: Result will start with activities whose start date is after specified value. (UTC) :type after: datetime.datetime or str or None :param limit: How many maximum activities to return. :type limit: int or None :return: An iterator of :class:`stravalib.model.Activity` objects. :rtype: :class:`BatchedResultsIterator` """
if before: before = self._utc_datetime_to_epoch(before) if after: after = self._utc_datetime_to_epoch(after) params = dict(before=before, after=after) result_fetcher = functools.partial(self.protocol.get, '/athlete/activities', **params) return BatchedResultsIterator(entity=model.Activity, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_athlete(self, athlete_id=None): """ Gets the specified athlete; if athlete_id is None then retrieves a detail-level representation of currently authenticated athlete; otherwise summary-level representation returned of athlete. http://strava.github.io/api/v3/athlete/#get-details http://strava.github.io/api/v3/athlete/#get-another-details :return: The athlete model object. :rtype: :class:`stravalib.model.Athlete` """
if athlete_id is None: raw = self.protocol.get('/athlete') else: raise NotImplementedError("The /athletes/{id} endpoint was removed by Strava. " "See https://developers.strava.com/docs/january-2018-update/") # raw = self.protocol.get('/athletes/{athlete_id}', athlete_id=athlete_id) return model.Athlete.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_athlete(self, city=None, state=None, country=None, sex=None, weight=None): """ Updates the properties of the authorized athlete. http://strava.github.io/api/v3/athlete/#update :param city: City the athlete lives in :param state: State the athlete lives in :param country: Country the athlete lives in :param sex: Sex of the athlete :param weight: Weight of the athlete in kg (float) :return: The updated athlete :rtype: :class:`stravalib.model.Athlete` """
params = {'city': city, 'state': state, 'country': country, 'sex': sex} params = {k: v for (k, v) in params.items() if v is not None} if weight is not None: params['weight'] = float(weight) raw_athlete = self.protocol.put('/athlete', **params) return model.Athlete.deserialize(raw_athlete, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_athlete_stats(self, athlete_id=None): """ Returns Statistics for the athlete. athlete_id must be the id of the authenticated athlete or left blank. If it is left blank two requests will be made - first to get the authenticated athlete's id and second to get the Stats. http://strava.github.io/api/v3/athlete/#stats :return: A model containing the Stats :rtype: :py:class:`stravalib.model.AthleteStats` """
if athlete_id is None: athlete_id = self.get_athlete().id raw = self.protocol.get('/athletes/{id}/stats', id=athlete_id) # TODO: Better error handling - this will return a 401 if this athlete # is not the authenticated athlete. return model.AthleteStats.deserialize(raw)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_athlete_clubs(self): """ List the clubs for the currently authenticated athlete. http://strava.github.io/api/v3/clubs/#get-athletes :return: A list of :class:`stravalib.model.Club` :rtype: :py:class:`list` """
club_structs = self.protocol.get('/athlete/clubs') return [model.Club.deserialize(raw, bind_client=self) for raw in club_structs]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_club(self, club_id): """ Return a specific club object. http://strava.github.io/api/v3/clubs/#get-details :param club_id: The ID of the club to fetch. :type club_id: int :rtype: :class:`stravalib.model.Club` """
raw = self.protocol.get("/clubs/{id}", id=club_id) return model.Club.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_club_members(self, club_id, limit=None): """ Gets the member objects for specified club ID. http://strava.github.io/api/v3/clubs/#get-members :param club_id: The numeric ID for the club. :type club_id: int :param limit: Maximum number of athletes to return. (default unlimited) :type limit: int :return: An iterator of :class:`stravalib.model.Athlete` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/clubs/{id}/members', id=club_id) return BatchedResultsIterator(entity=model.Athlete, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_club_activities(self, club_id, limit=None): """ Gets the activities associated with specified club. http://strava.github.io/api/v3/clubs/#get-activities :param club_id: The numeric ID for the club. :type club_id: int :param limit: Maximum number of activities to return. (default unlimited) :type limit: int :return: An iterator of :class:`stravalib.model.Activity` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/clubs/{id}/activities', id=club_id) return BatchedResultsIterator(entity=model.Activity, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity(self, activity_id, include_all_efforts=False): """ Gets specified activity. Will be detail-level if owned by authenticated user; otherwise summary-level. http://strava.github.io/api/v3/activities/#get-details :param activity_id: The ID of activity to fetch. :type activity_id: int :param inclue_all_efforts: Whether to include segment efforts - only available to the owner of the activty. :type include_all_efforts: bool :rtype: :class:`stravalib.model.Activity` """
raw = self.protocol.get('/activities/{id}', id=activity_id, include_all_efforts=include_all_efforts) return model.Activity.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_activity(self, name, activity_type, start_date_local, elapsed_time, description=None, distance=None): """ Create a new manual activity. If you would like to create an activity from an uploaded GPS file, see the :meth:`stravalib.client.Client.upload_activity` method instead. :param name: The name of the activity. :type name: str :param activity_type: The activity type (case-insensitive). Possible values: ride, run, swim, workout, hike, walk, nordicski, alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski, windsurf, workout, snowboard, snowshoe :type activity_type: str :param start_date_local: Local date/time of activity start. (TZ info will be ignored) :type start_date_local: :class:`datetime.datetime` or string in ISO8601 format. :param elapsed_time: The time in seconds or a :class:`datetime.timedelta` object. :type elapsed_time: :class:`datetime.timedelta` or int (seconds) :param description: The description for the activity. :type description: str :param distance: The distance in meters (float) or a :class:`units.quantity.Quantity` instance. :type distance: :class:`units.quantity.Quantity` or float (meters) """
if isinstance(elapsed_time, timedelta): elapsed_time = unithelper.timedelta_to_seconds(elapsed_time) if isinstance(distance, Quantity): distance = float(unithelper.meters(distance)) if isinstance(start_date_local, datetime): start_date_local = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ") if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]: raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES)) params = dict(name=name, type=activity_type, start_date_local=start_date_local, elapsed_time=elapsed_time) if description is not None: params['description'] = description if distance is not None: params['distance'] = distance raw_activity = self.protocol.post('/activities', **params) return model.Activity.deserialize(raw_activity, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_activity(self, activity_id, name=None, activity_type=None, private=None, commute=None, trainer=None, gear_id=None, description=None,device_name=None): """ Updates the properties of a specific activity. http://strava.github.io/api/v3/activities/#put-updates :param activity_id: The ID of the activity to update. :type activity_id: int :param name: The name of the activity. :param activity_type: The activity type (case-insensitive). Possible values: ride, run, swim, workout, hike, walk, nordicski, alpineski, backcountryski, iceskate, inlineskate, kitesurf, rollerski, windsurf, workout, snowboard, snowshoe :param private: Whether the activity is private. :param commute: Whether the activity is a commute. :param trainer: Whether this is a trainer activity. :param gear_id: Alpha-numeric ID of gear (bike, shoes) used on this activity. :param description: Description for the activity. :param device_name: Device name for the activity :return: The updated activity. :rtype: :class:`stravalib.model.Activity` """
# Convert the kwargs into a params dict params = {} if name is not None: params['name'] = name if activity_type is not None: if not activity_type.lower() in [t.lower() for t in model.Activity.TYPES]: raise ValueError("Invalid activity type: {0}. Possible values: {1!r}".format(activity_type, model.Activity.TYPES)) params['type'] = activity_type if private is not None: params['private'] = int(private) if commute is not None: params['commute'] = int(commute) if trainer is not None: params['trainer'] = int(trainer) if gear_id is not None: params['gear_id'] = gear_id if description is not None: params['description'] = description if device_name is not None: params['device_name'] = device_name raw_activity = self.protocol.put('/activities/{activity_id}', activity_id=activity_id, **params) return model.Activity.deserialize(raw_activity, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_zones(self, activity_id): """ Gets zones for activity. Requires premium account. http://strava.github.io/api/v3/activities/#zones :param activity_id: The activity for which to zones. :type activity_id: int :return: An list of :class:`stravalib.model.ActivityComment` objects. :rtype: :py:class:`list` """
zones = self.protocol.get('/activities/{id}/zones', id=activity_id) # We use a factory to give us the correct zone based on type. return [model.BaseActivityZone.deserialize(z, bind_client=self) for z in zones]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_comments(self, activity_id, markdown=False, limit=None): """ Gets the comments for an activity. http://strava.github.io/api/v3/comments/#list :param activity_id: The activity for which to fetch comments. :type activity_id: int :param markdown: Whether to include markdown in comments (default is false/filterout). :type markdown: bool :param limit: Max rows to return (default unlimited). :type limit: int :return: An iterator of :class:`stravalib.model.ActivityComment` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/comments', id=activity_id, markdown=int(markdown)) return BatchedResultsIterator(entity=model.ActivityComment, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_kudos(self, activity_id, limit=None): """ Gets the kudos for an activity. http://strava.github.io/api/v3/kudos/#list :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param limit: Max rows to return (default unlimited). :type limit: int :return: An iterator of :class:`stravalib.model.ActivityKudos` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/kudos', id=activity_id) return BatchedResultsIterator(entity=model.ActivityKudos, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_photos(self, activity_id, size=None, only_instagram=False): """ Gets the photos from an activity. http://strava.github.io/api/v3/photos/ :param activity_id: The activity for which to fetch kudos. :type activity_id: int :param size: the requested size of the activity's photos. URLs for the photos will be returned that best match the requested size. If not included, the smallest size is returned :type size: int :param only_instagram: Parameter to preserve legacy behavior of only returning Instagram photos. :type only_instagram: bool :return: An iterator of :class:`stravalib.model.ActivityPhoto` objects. :rtype: :class:`BatchedResultsIterator` """
params = {} if not only_instagram: params['photo_sources'] = 'true' if size is not None: params['size'] = size result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/photos', id=activity_id, **params) return BatchedResultsIterator(entity=model.ActivityPhoto, bind_client=self, result_fetcher=result_fetcher)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_laps(self, activity_id): """ Gets the laps from an activity. http://strava.github.io/api/v3/activities/#laps :param activity_id: The activity for which to fetch laps. :type activity_id: int :return: An iterator of :class:`stravalib.model.ActivityLaps` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/laps', id=activity_id) return BatchedResultsIterator(entity=model.ActivityLap, bind_client=self, result_fetcher=result_fetcher)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_gear(self, gear_id): """ Get details for an item of gear. http://strava.github.io/api/v3/gear/#show :param gear_id: The gear id. :type gear_id: str :return: The Bike or Shoe subclass object. :rtype: :class:`stravalib.model.Gear` """
return model.Gear.deserialize(self.protocol.get('/gear/{id}', id=gear_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_segment_effort(self, effort_id): """ Return a specific segment effort by ID. http://strava.github.io/api/v3/efforts/#retrieve :param effort_id: The id of associated effort to fetch. :type effort_id: int :return: The specified effort on a segment. :rtype: :class:`stravalib.model.SegmentEffort` """
return model.SegmentEffort.deserialize(self.protocol.get('/segment_efforts/{id}', id=effort_id))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_segment(self, segment_id): """ Gets a specific segment by ID. http://strava.github.io/api/v3/segments/#retrieve :param segment_id: The segment to fetch. :type segment_id: int :return: A segment object. :rtype: :class:`stravalib.model.Segment` """
return model.Segment.deserialize(self.protocol.get('/segments/{id}', id=segment_id), bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_starred_segments(self, limit=None): """ Returns a summary representation of the segments starred by the authenticated user. Pagination is supported. http://strava.github.io/api/v3/segments/#starred :param limit: (optional), limit number of starred segments returned. :type limit: int :return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user. :rtype: :class:`BatchedResultsIterator` """
params = {} if limit is not None: params["limit"] = limit result_fetcher = functools.partial(self.protocol.get, '/segments/starred') return BatchedResultsIterator(entity=model.Segment, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_athlete_starred_segments(self, athlete_id, limit=None): """ Returns a summary representation of the segments starred by the specified athlete. Pagination is supported. http://strava.github.io/api/v3/segments/#starred :param athlete_id: The ID of the athlete. :type athlete_id: int :param limit: (optional), limit number of starred segments returned. :type limit: int :return: An iterator of :class:`stravalib.model.Segment` starred by authenticated user. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/athletes/{id}/segments/starred', id=athlete_id) return BatchedResultsIterator(entity=model.Segment, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_segment_leaderboard(self, segment_id, gender=None, age_group=None, weight_class=None, following=None, club_id=None, timeframe=None, top_results_limit=None, page=None, context_entries = None): """ Gets the leaderboard for a segment. http://strava.github.io/api/v3/segments/#leaderboard Note that by default Strava will return the top 10 results, and if the current user has ridden that segment, the current user's result along with the two results above in rank and the two results below will be included. The top X results can be configured by setting the top_results_limit parameter; however, the other 5 results will be included if the current user has ridden that segment. (i.e. if you specify top_results_limit=15, you will get a total of 20 entries back.) :param segment_id: ID of the segment. :type segment_id: int :param gender: (optional) 'M' or 'F' :type gender: str :param age_group: (optional) '0_24', '25_34', '35_44', '45_54', '55_64', '65_plus' :type age_group: str :param weight_class: (optional) pounds '0_124', '125_149', '150_164', '165_179', '180_199', '200_plus' or kilograms '0_54', '55_64', '65_74', '75_84', '85_94', '95_plus' :type weight_class: str :param following: (optional) Limit to athletes current user is following. :type following: bool :param club_id: (optional) limit to specific club :type club_id: int :param timeframe: (optional) 'this_year', 'this_month', 'this_week', 'today' :type timeframe: str :param top_results_limit: (optional, strava default is 10 + 5 from end) How many of leading leaderboard entries to display. See description for why this is a little confusing. :type top_results_limit: int :param page: (optional, strava default is 1) Page number of leaderboard to return, sorted by highest ranking leaders :type page: int :param context_entries: (optional, strava default is 2, max is 15) number of entries surrounding requesting athlete to return :type context_entries: int :return: The SegmentLeaderboard for the specified page (default: 1) :rtype: :class:`stravalib.model.SegmentLeaderboard` """
params = {} if gender is not None: if gender.upper() not in ('M', 'F'): raise ValueError("Invalid gender: {0}. Possible values: 'M' or 'F'".format(gender)) params['gender'] = gender valid_age_groups = ('0_24', '25_34', '35_44', '45_54', '55_64', '65_plus') if age_group is not None: if not age_group in valid_age_groups: raise ValueError("Invalid age group: {0}. Possible values: {1!r}".format(age_group, valid_age_groups)) params['age_group'] = age_group valid_weight_classes = ('0_124', '125_149', '150_164', '165_179', '180_199', '200_plus', '0_54', '55_64', '65_74', '75_84', '85_94', '95_plus') if weight_class is not None: if not weight_class in valid_weight_classes: raise ValueError("Invalid weight class: {0}. Possible values: {1!r}".format(weight_class, valid_weight_classes)) params['weight_class'] = weight_class if following is not None: params['following'] = int(following) if club_id is not None: params['club_id'] = club_id if timeframe is not None: valid_timeframes = 'this_year', 'this_month', 'this_week', 'today' if not timeframe in valid_timeframes: raise ValueError("Invalid timeframe: {0}. Possible values: {1!r}".format(timeframe, valid_timeframes)) params['date_range'] = timeframe if top_results_limit is not None: params['per_page'] = top_results_limit if page is not None: params['page'] = page if context_entries is not None: params['context_entries'] = context_entries return model.SegmentLeaderboard.deserialize(self.protocol.get('/segments/{id}/leaderboard', id=segment_id, **params), bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_segment_efforts(self, segment_id, athlete_id=None, start_date_local=None, end_date_local=None, limit=None): """ Gets all efforts on a particular segment sorted by start_date_local Returns an array of segment effort summary representations sorted by start_date_local ascending or by elapsed_time if an athlete_id is provided. If no filtering parameters is provided all efforts for the segment will be returned. Date range filtering is accomplished using an inclusive start and end time, thus start_date_local and end_date_local must be sent together. For open ended ranges pick dates significantly in the past or future. The filtering is done over local time for the segment, so there is no need for timezone conversion. For example, all efforts on Jan. 1st, 2014 for a segment in San Francisco, CA can be fetched using 2014-01-01T00:00:00Z and 2014-01-01T23:59:59Z. http://strava.github.io/api/v3/segments/#all_efforts :param segment_id: ID of the segment. :type segment_id: param :int athlete_id: (optional) ID of athlete. :type athlete_id: int :param start_date_local: (optional) efforts before this date will be excluded. Either as ISO8601 or datetime object :type start_date_local: datetime.datetime or str :param end_date_local: (optional) efforts after this date will be excluded. Either as ISO8601 or datetime object :type end_date_local: datetime.datetime or str :param limit: (optional), limit number of efforts. :type limit: int :return: An iterator of :class:`stravalib.model.SegmentEffort` efforts on a segment. :rtype: :class:`BatchedResultsIterator` """
params = {"segment_id": segment_id} if athlete_id is not None: params['athlete_id'] = athlete_id if start_date_local: if isinstance(start_date_local, six.string_types): start_date_local = arrow.get(start_date_local).naive params["start_date_local"] = start_date_local.strftime("%Y-%m-%dT%H:%M:%SZ") if end_date_local: if isinstance(end_date_local, six.string_types): end_date_local = arrow.get(end_date_local).naive params["end_date_local"] = end_date_local.strftime("%Y-%m-%dT%H:%M:%SZ") if limit is not None: params["limit"] = limit result_fetcher = functools.partial(self.protocol.get, '/segments/{segment_id}/all_efforts', **params) return BatchedResultsIterator(entity=model.BaseEffort, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explore_segments(self, bounds, activity_type=None, min_cat=None, max_cat=None): """ Returns an array of up to 10 segments. http://strava.github.io/api/v3/segments/#explore :param bounds: list of bounding box corners lat/lon [sw.lat, sw.lng, ne.lat, ne.lng] (south,west,north,east) :type bounds: list of 4 floats or list of 2 (lat,lon) tuples :param activity_type: (optional, default is riding) 'running' or 'riding' :type activity_type: str :param min_cat: (optional) Minimum climb category filter :type min_cat: int :param max_cat: (optional) Maximum climb category filter :type max_cat: int :return: An list of :class:`stravalib.model.Segment`. :rtype: :py:class:`list` """
if len(bounds) == 2: bounds = (bounds[0][0], bounds[0][1], bounds[1][0], bounds[1][1]) elif len(bounds) != 4: raise ValueError("Invalid bounds specified: {0!r}. Must be list of 4 float values or list of 2 (lat,lon) tuples.") params = {'bounds': ','.join(str(b) for b in bounds)} valid_activity_types = ('riding', 'running') if activity_type is not None: if activity_type not in ('riding', 'running'): raise ValueError('Invalid activity type: {0}. Possible values: {1!r}'.format(activity_type, valid_activity_types)) params['activity_type'] = activity_type if min_cat is not None: params['min_cat'] = min_cat if max_cat is not None: params['max_cat'] = max_cat raw = self.protocol.get('/segments/explore', **params) return [model.SegmentExplorerResult.deserialize(v, bind_client=self) for v in raw['segments']]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_activity_streams(self, activity_id, types=None, resolution=None, series_type=None): """ Returns an streams for an activity. http://strava.github.io/api/v3/streams/#activity Streams represent the raw data of the uploaded file. External applications may only access this information for activities owned by the authenticated athlete. Streams are available in 11 different types. If the stream is not available for a particular activity it will be left out of the request results. Streams types are: time, latlng, distance, altitude, velocity_smooth, heartrate, cadence, watts, temp, moving, grade_smooth http://strava.github.io/api/v3/streams/#activity :param activity_id: The ID of activity. :type activity_id: int :param types: (optional) A list of the the types of streams to fetch. :type types: list :param resolution: (optional, default is 'all') indicates desired number of data points. 'low' (100), 'medium' (1000), 'high' (10000) or 'all'. :type resolution: str :param series_type: (optional, default is 'distance'. Relevant only if using resolution either 'time' or 'distance'. Used to index the streams if the stream is being reduced. :type series_type: str :return: An dictionary of :class:`stravalib.model.Stream` from the activity or None if there are no streams. :rtype: :py:class:`dict` """
# stream are comma seperated list if types is not None: types = ",".join(types) params = {} if resolution is not None: params["resolution"] = resolution if series_type is not None: params["series_type"] = series_type result_fetcher = functools.partial(self.protocol.get, '/activities/{id}/streams/{types}'.format(id=activity_id, types=types), **params) streams = BatchedResultsIterator(entity=model.Stream, bind_client=self, result_fetcher=result_fetcher) # Pack streams into dictionary try: return {i.type: i for i in streams} except exc.ObjectNotFound: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_effort_streams(self, effort_id, types=None, resolution=None, series_type=None): """ Returns an streams for an effort. http://strava.github.io/api/v3/streams/#effort Streams represent the raw data of the uploaded file. External applications may only access this information for activities owned by the authenticated athlete. Streams are available in 11 different types. If the stream is not available for a particular activity it will be left out of the request results. Streams types are: time, latlng, distance, altitude, velocity_smooth, heartrate, cadence, watts, temp, moving, grade_smooth http://strava.github.io/api/v3/streams/#effort :param effort_id: The ID of effort. :type effort_id: int :param types: (optional) A list of the the types of streams to fetch. :type types: list :param resolution: (optional, default is 'all') indicates desired number of data points. 'low' (100), 'medium' (1000), 'high' (10000) or 'all'. :type resolution: str :param series_type: (optional, default is 'distance'. Relevant only if using resolution either 'time' or 'distance'. Used to index the streams if the stream is being reduced. :type series_type: str :return: An dictionary of :class:`stravalib.model.Stream` from the effort. :rtype: :py:class:`dict` """
# stream are comma seperated list if types is not None: types = ",".join(types) params = {} if resolution is not None: params["resolution"] = resolution if series_type is not None: params["series_type"] = series_type result_fetcher = functools.partial(self.protocol.get, '/segment_efforts/{id}/streams/{types}'.format(id=effort_id, types=types), **params) streams = BatchedResultsIterator(entity=model.Stream, bind_client=self, result_fetcher=result_fetcher) # Pack streams into dictionary return {i.type: i for i in streams}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_running_race(self, race_id): """ Gets a running race for a given identifier.t http://strava.github.io/api/v3/running_races/#list :param race_id: id for the race :rtype: :class:`stravalib.model.RunningRace` """
raw = self.protocol.get('/running_races/{id}', id=race_id) return model.RunningRace.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_running_races(self, year=None): """ Gets a running races for a given year. http://strava.github.io/api/v3/running_races/#list :param year: year for the races (default current) :return: An iterator of :class:`stravalib.model.RunningRace` objects. :rtype: :class:`BatchedResultsIterator` """
if year is None: year = datetime.datetime.now().year params = {"year": year} result_fetcher = functools.partial(self.protocol.get, '/running_races', **params) return BatchedResultsIterator(entity=model.RunningRace, bind_client=self, result_fetcher=result_fetcher)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_routes(self, athlete_id=None, limit=None): """ Gets the routes list for an authenticated user. http://strava.github.io/api/v3/routes/#list :param athlete_id: id for the :param limit: Max rows to return (default unlimited). :type limit: int :return: An iterator of :class:`stravalib.model.Route` objects. :rtype: :class:`BatchedResultsIterator` """
if athlete_id is None: athlete_id = self.get_athlete().id result_fetcher = functools.partial(self.protocol.get, '/athletes/{id}/routes'.format(id=athlete_id)) return BatchedResultsIterator(entity=model.Route, bind_client=self, result_fetcher=result_fetcher, limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_route(self, route_id): """ Gets specified route. Will be detail-level if owned by authenticated user; otherwise summary-level. https://strava.github.io/api/v3/routes/#retreive :param route_id: The ID of route to fetch. :type route_id: int :rtype: :class:`stravalib.model.Route` """
raw = self.protocol.get('/routes/{id}', id=route_id) return model.Route.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_route_streams(self, route_id): """ Returns streams for a route. http://strava.github.io/api/v3/streams/#routes Streams represent the raw data of the saved route. External applications may access this information for all public routes and for the private routes of the authenticated athlete. The 3 available route stream types `distance`, `altitude` and `latlng` are always returned. http://strava.github.io/api/v3/streams/#routes :param activity_id: The ID of activity. :type activity_id: int :return: A dictionary of :class:`stravalib.model.Stream`from the route. :rtype: :py:class:`dict` """
result_fetcher = functools.partial(self.protocol.get, '/routes/{id}/streams/'.format(id=route_id)) streams = BatchedResultsIterator(entity=model.Stream, bind_client=self, result_fetcher=result_fetcher) # Pack streams into dictionary return {i.type: i for i in streams}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_subscription(self, client_id, client_secret, callback_url, object_type=model.Subscription.OBJECT_TYPE_ACTIVITY, aspect_type=model.Subscription.ASPECT_TYPE_CREATE, verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT): """ Creates a webhook event subscription. http://strava.github.io/api/partner/v3/events/#create-a-subscription :param client_id: application's ID, obtained during registration :type client_id: int :param client_secret: application's secret, obtained during registration :type client_secret: str :param callback_url: callback URL where Strava will first send a GET request to validate, then subsequently send POST requests with updates :type callback_url: str :param object_type: object_type (currently only `activity` is supported) :type object_type: str :param aspect_type: object_type (currently only `create` is supported) :type aspect_type: str :param verify_token: a token you can use to verify Strava's GET callback request :type verify_token: str :return: An instance of :class:`stravalib.model.Subscription`. :rtype: :class:`stravalib.model.Subscription` Notes: `object_type` and `aspect_type` are given defaults because there is currently only one valid value for each. `verify_token` is set to a default in the event that the author doesn't want to specify one. The appliction must have permission to make use of the webhook API. Access can be requested by contacting developers -at- strava.com. """
params = dict(client_id=client_id, client_secret=client_secret, object_type=object_type, aspect_type=aspect_type, callback_url=callback_url, verify_token=verify_token) raw = self.protocol.post('/push_subscriptions', use_webhook_server=True, **params) return model.Subscription.deserialize(raw, bind_client=self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_subscription_callback(self, raw, verify_token=model.Subscription.VERIFY_TOKEN_DEFAULT): """ Validate callback request and return valid response with challenge. :return: The JSON response expected by Strava to the challenge request. :rtype: Dict[str, str] """
callback = model.SubscriptionCallback.deserialize(raw) callback.validate(verify_token) response_raw = {'hub.challenge': callback.hub_challenge} return response_raw
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_subscriptions(self, client_id, client_secret): """ List current webhook event subscriptions in place for the current application. http://strava.github.io/api/partner/v3/events/#list-push-subscriptions :param client_id: application's ID, obtained during registration :type client_id: int :param client_secret: application's secret, obtained during registration :type client_secret: str :return: An iterator of :class:`stravalib.model.Subscription` objects. :rtype: :class:`BatchedResultsIterator` """
result_fetcher = functools.partial(self.protocol.get, '/push_subscriptions', client_id=client_id, client_secret=client_secret, use_webhook_server=True) return BatchedResultsIterator(entity=model.Subscription, bind_client=self, result_fetcher=result_fetcher)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_subscription(self, subscription_id, client_id, client_secret): """ Unsubscribe from webhook events for an existing subscription. http://strava.github.io/api/partner/v3/events/#delete-a-subscription :param subscription_id: ID of subscription to remove. :type subscription_id: int :param client_id: application's ID, obtained during registration :type client_id: int :param client_secret: application's secret, obtained during registration :type client_secret: str """
self.protocol.delete('/push_subscriptions/{id}', id=subscription_id, client_id=client_id, client_secret=client_secret, use_webhook_server=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fill_buffer(self): """ Fills the internal size-50 buffer from Strava API. """
# If we cannot fetch anymore from the server then we're done here. if self._all_results_fetched: self._eof() raw_results = self.result_fetcher(page=self._page, per_page=self.per_page) entities = [] for raw in raw_results: entities.append(self.entity.deserialize(raw, bind_client=self.bind_client)) self._buffer = collections.deque(entities) self.log.debug("Requested page {0} (got: {1} items)".format(self._page, len(self._buffer))) if len(self._buffer) < self.per_page: self._all_results_fetched = True self._page += 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_from_response(self, response, raise_exc=True): """ Updates internal state of object. :param response: The response object (dict). :type response: :py:class:`dict` :param raise_exc: Whether to raise an exception if the response indicates an error state. (default True) :type raise_exc: bool :raise stravalib.exc.ActivityUploadFailed: If the response indicates an error and raise_exc is True. """
self.upload_id = response.get('id') self.external_id = response.get('external_id') self.activity_id = response.get('activity_id') self.status = response.get('status') or response.get('message') if response.get('error'): self.error = response.get('error') elif response.get('errors'): # This appears to be an undocumented API; ths is a bit of a hack for now. self.error = str(response.get('errors')) else: self.error = None if raise_exc: self.raise_for_error()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, timeout=None, poll_interval=1.0): """ Wait for the upload to complete or to err out. Will return the resulting Activity or raise an exception if the upload fails. :param timeout: The max seconds to wait. Will raise TimeoutExceeded exception if this time passes without success or error response. :type timeout: float :param poll_interval: How long to wait between upload checks. Strava recommends 1s minimum. (default 1.0s) :type poll_interval: float :return: The uploaded Activity object (fetched from server) :rtype: :class:`stravalib.model.Activity` :raise stravalib.exc.TimeoutExceeded: If a timeout was specified and activity is still processing after timeout has elapsed. :raise stravalib.exc.ActivityUploadFailed: If the poll returns an error. """
start = time.time() while self.activity_id is None: self.poll() time.sleep(poll_interval) if timeout and (time.time() - start) > timeout: raise exc.TimeoutExceeded() # If we got this far, we must have an activity! return self.client.get_activity(self.activity_id)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def full_photos(self): """ Gets a list of photos using default options. :class:`list` of :class:`stravalib.model.ActivityPhoto` objects for this activity. """
if self._photos is None: if self.total_photo_count > 0: self.assert_bind_client() self._photos = self.bind_client.get_activity_photos(self.id, only_instagram=False) else: self._photos = [] return self._photos
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, key, default=None): """ Retreive a value from the cache. In the event the value does not exist, return the ``default``. """
key = self.make_key(key) if self.debug: return default try: value = self.database[key] except KeyError: self.metrics['misses'] += 1 return default else: self.metrics['hits'] += 1 return pickle.loads(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, key, value, timeout=None): """ Cache the given ``value`` in the specified ``key``. If no timeout is specified, the default timeout will be used. """
key = self.make_key(key) if timeout is None: timeout = self.default_timeout if self.debug: return True pickled_value = pickle.dumps(value) self.metrics['writes'] += 1 if timeout: return self.database.setex(key, int(timeout), pickled_value) else: return self.database.set(key, pickled_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, key): """Remove the given key from the cache."""
if not self.debug: self.database.delete(self.make_key(key))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self): """Remove all cached objects from the database."""
keys = list(self.keys()) if keys: return self.database.delete(*keys)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cached_property(self, key_fn=_key_fn, timeout=None): """ Decorator that will transparently cache calls to the wrapped method. The method will be exposed as a property. Usage:: cache = Cache(my_database) class Clock(object): @cache.cached_property() def now(self): return datetime.datetime.now() clock = Clock() print clock.now """
this = self class _cached_property(object): def __init__(self, fn): self._fn = this.cached(key_fn, timeout)(fn) def __get__(self, instance, instance_type=None): if instance is None: return self return self._fn(instance) def __delete__(self, obj): self._fn.bust(obj) def __set__(self, instance, value): raise ValueError('Cannot set value of a cached property.') def decorator(fn): return _cached_property(fn) return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_async(self, key_fn=_key_fn, timeout=3600): """ Decorator that will execute the cached function in a separate thread. The function will immediately return, returning a callable to the user. This callable can be used to check for a return value. For details, see the :ref:`cache-async` section of the docs. :param key_fn: Function used to generate cache key. :param int timeout: Cache timeout in seconds. :returns: A new function which can be called to retrieve the return value of the decorated function. """
def decorator(fn): wrapped = self.cached(key_fn, timeout)(fn) @wraps(fn) def inner(*args, **kwargs): q = Queue() def _sub_fn(): q.put(wrapped(*args, **kwargs)) def _get_value(block=True, timeout=None): if not hasattr(_get_value, '_return_value'): result = q.get(block=block, timeout=timeout) _get_value._return_value = result return _get_value._return_value thread = threading.Thread(target=_sub_fn) thread.start() return _get_value return inner return decorator
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store(self, obj_id, title=None, data=None, obj_type=None): """ Store data in the autocomplete index. :param obj_id: Either a unique identifier for the object being indexed or the word/phrase to be indexed. :param title: The word or phrase to be indexed. If not provided, the ``obj_id`` will be used as the title. :param data: Arbitrary data to index, which will be returned when searching for results. If not provided, this value will default to the title being indexed. :param obj_type: Optional object type. Since results can be boosted by type, you might find it useful to specify this when storing multiple types of objects. You have the option of storing several types of data as defined by the parameters. At the minimum, you can specify an ``obj_id``, which will be the word or phrase you wish to index. Alternatively, if for instance you were indexing blog posts, you might specify all parameters. """
if title is None: title = obj_id if data is None: data = title obj_type = obj_type or '' if self._use_json: data = json.dumps(data) combined_id = self.object_key(obj_id, obj_type) if self.exists(obj_id, obj_type): stored_title = self._title_data[combined_id] if stored_title == title: self._data[combined_id] = data return else: self.remove(obj_id, obj_type) self._data[combined_id] = data self._title_data[combined_id] = title clean_title = ' '.join(self.tokenize_title(title)) title_score = self.score_token(clean_title) for idx, word in enumerate(self.tokenize_title(title)): word_score = self.score_token(word) position_score = word_score + (self._offset * idx) key_score = position_score + title_score for substring in self.substrings(word): self.database.zadd(self.word_key(substring), {combined_id: key_score}) return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exists(self, obj_id, obj_type=None): """ Return whether the given object exists in the search index. :param obj_id: The object's unique identifier. :param obj_type: The object's type. """
return self.object_key(obj_id, obj_type) in self._data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def boost_object(self, obj_id=None, obj_type=None, multiplier=1.1, relative=True): """ Boost search results for the given object or type by the amount specified. When the ``multiplier`` is greater than 1, the results will percolate to the top. Values between 0 and 1 will percolate results to the bottom. Either an ``obj_id`` or ``obj_type`` (or both) must be specified. :param obj_id: An object's unique identifier (optional). :param obj_type: The object's type (optional). :param multiplier: A positive floating-point number. :param relative: If ``True``, then any pre-existing saved boost will be updated using the given multiplier. Examples: .. code-block:: python # Make all objects of type=photos percolate to top. ac.boost_object(obj_type='photo', multiplier=2.0) # Boost a particularly popular blog entry. ac.boost_object( popular_entry.id, 'entry', multipler=5.0, relative=False) """
combined_id = self.object_key(obj_id or '', obj_type or '') if relative: current = float(self._boosts[combined_id] or 1.0) self._boosts[combined_id] = current * multiplier else: self._boosts[combined_id] = multiplier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list_data(self): """ Return all the data stored in the autocomplete index. If the data was stored as serialized JSON, then it will be de-serialized before being returned. :rtype: list """
fn = (lambda v: json.loads(decode(v))) if self._use_json else decode return map(fn, self._data.values())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flush(self, batch_size=1000): """ Delete all autocomplete indexes and metadata. """
keys = self.database.keys(self.namespace + ':*') for i in range(0, len(keys), batch_size): self.database.delete(*keys[i:i + batch_size])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def metaphone(self, words): """ Apply the double metaphone algorithm to the given words. Using metaphone allows the search index to tolerate misspellings and small typos. Example:: ('ALRS', 'FLRS') ('P0N', 'PTN') ('P0N', 'PTN') """
for word in words: r = 0 for w in double_metaphone(word): if w: w = w.strip() if w: r += 1 yield w if not r: yield word
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tokenize(self, value): """ Split the incoming value into tokens and process each token, optionally stemming or running metaphone. :returns: A ``dict`` mapping token to score. The score is based on the relative frequency of the word in the document. """
words = self.split_phrase(decode(value).lower()) if self._stopwords: words = [w for w in words if w not in self._stopwords] if self._min_word_length: words = [w for w in words if len(w) >= self._min_word_length] fraction = 1. / (len(words) + 1) # Prevent division by zero. # Apply optional transformations. if self._use_stemmer: words = self.stem(words) if self._use_metaphone: words = self.metaphone(words) scores = {} for word in words: scores.setdefault(word, 0) scores[word] += fraction return scores
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expire(self, ttl=None): """ Expire the given key in the given number of seconds. If ``ttl`` is ``None``, then any expiry will be cleared and key will be persisted. """
if ttl is not None: self.database.expire(self.key, ttl) else: self.database.persist(self.key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pexpire(self, ttl=None): """ Expire the given key in the given number of milliseconds. If ``ttl`` is ``None``, then any expiry will be cleared and key will be persisted. """
if ttl is not None: self.database.pexpire(self.key, ttl) else: self.database.persist(self.key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, pattern, count=None): """ Search the keys of the given hash using the specified pattern. :param str pattern: Pattern used to match keys. :param int count: Limit number of results returned. :returns: An iterator yielding matching key/value pairs. """
return self._scan(match=pattern, count=count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(cls, database, key, data, clear=False): """ Create and populate a Hash object from a data dictionary. """
hsh = cls(database, key) if clear: hsh.clear() hsh.update(data) return hsh
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_list(self, decode=False): """ Return a list containing all the items in the list. """
items = self.database.lrange(self.key, 0, -1) return [_decode(item) for item in items] if decode else items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_list(cls, database, key, data, clear=False): """ Create and populate a List object from a data list. """
lst = cls(database, key) if clear: lst.clear() lst.extend(data) return lst
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diffstore(self, dest, *others): """ Store the set difference of the current set and one or more others in a new key. :param dest: the name of the key to store set difference :param others: One or more :py:class:`Set` instances :returns: A :py:class:`Set` referencing ``dest``. """
keys = [self.key] keys.extend([other.key for other in others]) self.database.sdiffstore(dest, keys) return self.database.Set(dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interstore(self, dest, *others): """ Store the intersection of the current set and one or more others in a new key. :param dest: the name of the key to store intersection :param others: One or more :py:class:`Set` instances :returns: A :py:class:`Set` referencing ``dest``. """
keys = [self.key] keys.extend([other.key for other in others]) self.database.sinterstore(dest, keys) return self.database.Set(dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_set(self, decode=False): """ Return a Python set containing all the items in the collection. """
items = self.database.smembers(self.key) return set(_decode(item) for item in items) if decode else items
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_set(cls, database, key, data, clear=False): """ Create and populate a Set object from a data set. """
s = cls(database, key) if clear: s.clear() s.add(*data) return s
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rank(self, item, reverse=False): """Return the rank of the given item."""
fn = reverse and self.database.zrevrank or self.database.zrank return fn(self.key, item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def count(self, low, high=None): """ Return the number of items between the given bounds. """
if high is None: high = low return self.database.zcount(self.key, low, high)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def range(self, low, high, with_scores=False, desc=False, reverse=False): """ Return a range of items between ``low`` and ``high``. By default scores will not be included, but this can be controlled via the ``with_scores`` parameter. :param low: Lower bound. :param high: Upper bound. :param bool with_scores: Whether the range should include the scores along with the items. :param bool desc: Whether to sort the results descendingly. :param bool reverse: Whether to select the range in reverse. """
if reverse: return self.database.zrevrange(self.key, low, high, with_scores) else: return self.database.zrange(self.key, low, high, desc, with_scores)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_by_score(self, low, high=None): """ Remove elements from the ZSet by their score. :param low: Lower bound. :param high: Upper bound. """
if high is None: high = low return self.database.zremrangebyscore(self.key, low, high)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def incr(self, key, incr_by=1.): """ Increment the score of an item in the ZSet. :param key: Item to increment. :param incr_by: Amount to increment item's score. """
return self.database.zincrby(self.key, incr_by, key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interstore(self, dest, *others, **kwargs): """ Store the intersection of the current zset and one or more others in a new key. :param dest: the name of the key to store intersection :param others: One or more :py:class:`ZSet` instances :returns: A :py:class:`ZSet` referencing ``dest``. """
keys = [self.key] keys.extend([other.key for other in others]) self.database.zinterstore(dest, keys, **kwargs) return self.database.ZSet(dest)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_dict(cls, database, key, data, clear=False): """ Create and populate a ZSet object from a data dictionary. """
zset = cls(database, key) if clear: zset.clear() zset.add(data) return zset
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, value): """Append a new value to the end of the array."""
self.database.run_script( 'array_append', keys=[self.key], args=[value])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extend(self, values): """Extend the array, appending the given values."""
self.database.run_script( 'array_extend', keys=[self.key], args=values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pop(self, idx=None): """ Remove an item from the array. By default this will be the last item by index, but any index can be specified. """
if idx is not None: return self.database.run_script( 'array_remove', keys=[self.key], args=[idx]) else: return self.database.run_script( 'array_pop', keys=[self.key], args=[])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def as_list(self, decode=False): """ Return a list of items in the array. """
return [_decode(i) for i in self] if decode else list(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_list(cls, database, key, data, clear=False): """ Create and populate an Array object from a data dictionary. """
arr = cls(database, key) if clear: arr.clear() arr.extend(data) return arr
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, data, id='*', maxlen=None, approximate=True): """ Add data to a stream. :param dict data: data to add to stream :param id: identifier for message ('*' to automatically append) :param maxlen: maximum length for stream :param approximate: allow stream max length to be approximate :returns: the added message id. """
return self.database.xadd(self.key, data, id, maxlen, approximate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def range(self, start='-', stop='+', count=None): """ Read a range of values from a stream. :param start: start key of range (inclusive) or '-' for oldest message :param stop: stop key of range (inclusive) or '+' for newest message :param count: limit number of messages returned """
return self.database.xrange(self.key, start, stop, count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revrange(self, start='+', stop='-', count=None): """ Read a range of values from a stream in reverse. :param start: start key of range (inclusive) or '+' for newest message :param stop: stop key of range (inclusive) or '-' for oldest message :param count: limit number of messages returned """
return self.database.xrevrange(self.key, start, stop, count)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, count=None, block=None, last_id=None): """ Monitor stream for new data. :param int count: limit number of messages returned :param int block: milliseconds to block, 0 for indefinitely :param last_id: Last id read (an exclusive lower-bound). If the '$' value is given, we will only read values added *after* our command started blocking. :returns: a list of (message id, data) 2-tuples. """
if last_id is None: last_id = '0-0' resp = self.database.xread({self.key: _decode(last_id)}, count, block) # resp is a 2-tuple of stream name -> message list. return resp[0][1] if resp else []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trim(self, count, approximate=True): """ Trim the stream to the given "count" of messages, discarding the oldest messages first. :param count: maximum size of stream :param approximate: allow size to be approximate """
return self.database.xtrim(self.key, count, approximate)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pending(self, start='-', stop='+', count=1000, consumer=None): """ List pending messages within the consumer group for this stream. :param start: start id (or '-' for oldest pending) :param stop: stop id (or '+' for newest pending) :param count: limit number of messages returned :param consumer: restrict message list to the given consumer :returns: A list containing status for each pending message. Each pending message returns [id, consumer, idle time, deliveries]. """
return self.database.xpending_range(self.key, self.group, start, stop, count, consumer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_consumer(self, consumer=None): """ Remove a specific consumer from a consumer group. :consumer: name of consumer to delete. If not provided, will be the default consumer for this stream. :returns: number of pending messages that the consumer had before being deleted. """
if consumer is None: consumer = self._consumer return self.database.xgroup_delconsumer(self.key, self.group, consumer)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, ensure_keys_exist=True, mkstream=False): """ Create the consumer group and register it with the group's stream keys. :param ensure_keys_exist: Ensure that the streams exist before creating the consumer group. Streams that do not exist will be created. :param mkstream: Use the "MKSTREAM" option to ensure stream exists (may require unstable version of Redis). """
if ensure_keys_exist: for key in self.keys: if not self.database.exists(key): msg_id = self.database.xadd(key, {'': ''}, id=b'0-1') self.database.xdel(key, msg_id) elif self.database.type(key) != b'stream': raise ValueError('Consumer group key "%s" exists and is ' 'not a stream. To prevent data-loss ' 'this key will not be deleted.') resp = {} # Mapping of key -> last-read message ID. for key, value in self.keys.items(): try: resp[key] = self.database.xgroup_create(key, self.name, value, mkstream) except ResponseError as exc: if exception_message(exc).startswith('BUSYGROUP'): resp[key] = False else: raise return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self): """ Destroy the consumer group. """
resp = {} for key in self.keys: resp[key] = self.database.xgroup_destroy(key, self.name) return resp
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self, fmt, offset): """ Get the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. u8 for an unsigned 8-bit integer. :param int offset: offset (in number of bits). :returns: a :py:class:`BitFieldOperation` instance. """
bfo = BitFieldOperation(self.database, self.key) return bfo.get(fmt, offset)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set(self, fmt, offset, value): """ Set the value of a given bitfield. :param fmt: format-string for the bitfield being read, e.g. u8 for an unsigned 8-bit integer. :param int offset: offset (in number of bits). :param int value: value to set at the given position. :returns: a :py:class:`BitFieldOperation` instance. """
bfo = BitFieldOperation(self.database, self.key) return bfo.set(fmt, offset, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, data): """ Add an item to the bloomfilter. :param bytes data: a bytestring representing the item to add. """
bfo = BitFieldOperation(self.database, self.key) for bit_index in self._get_seeds(data): bfo.set('u1', bit_index, 1) bfo.execute()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(self, data): """ Check if an item has been added to the bloomfilter. :param bytes data: a bytestring representing the item to check. :returns: a boolean indicating whether or not the item is present in the bloomfilter. False-positives are possible, but a negative return value is definitive. """
bfo = BitFieldOperation(self.database, self.key) for bit_index in self._get_seeds(data): bfo.get('u1', bit_index) return all(bfo.execute())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_many(self, items): """ Store multiple subject-predicate-object triples in the database. :param items: A list of (subj, pred, obj) 3-tuples. """
with self.walrus.atomic(): for item in items: self.store(*item)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, s, p, o): """Remove the given subj-pred-obj triple from the database."""
with self.walrus.atomic(): for key in self.keys_for_values(s, p, o): del self._z[key]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search(self, *conditions): """ Given a set of conditions, return all values that satisfy the conditions for a given set of variables. For example, suppose I wanted to find all of my friends who live in Kansas: .. code-block:: python X = graph.v.X results = graph.search( {'s': 'charlie', 'p': 'friends', 'o': X}, {'s': X, 'p': 'lives', 'o': 'Kansas'}) The return value consists of a dictionary keyed by variable, whose values are ``set`` objects containing the values that satisfy the query clauses, e.g.: .. code-block:: python print results # Result has one key, for our "X" variable. The value is the set # of my friends that live in Kansas. # {'X': {'huey', 'nuggie'}} # We can assume the following triples exist: # ('charlie', 'friends', 'huey') # ('charlie', 'friends', 'nuggie') # ('huey', 'lives', 'Kansas') # ('nuggie', 'lives', 'Kansas') """
results = {} for condition in conditions: if isinstance(condition, tuple): query = dict(zip('spo', condition)) else: query = condition.copy() materialized = {} targets = [] for part in ('s', 'p', 'o'): if isinstance(query[part], Variable): variable = query.pop(part) materialized[part] = set() targets.append((variable, part)) # Potentially rather than popping all the variables, we could use # the result values from a previous condition and do O(results) # loops looking for a single variable. for result in self.query(**query): ok = True for var, part in targets: if var in results and result[part] not in results[var]: ok = False break if ok: for var, part in targets: materialized[part].add(result[part]) for var, part in targets: if var in results: results[var] &= materialized[part] else: results[var] = materialized[part] return dict((var.name, vals) for (var, vals) in results.items())