How to use filter_by_prefix method in autotest

Best Python code snippet using autotest_python

api.py

Source:api.py Github

copy

Full Screen

1import copy2import itertools3import logging4import string5from performanceplatform.client import DataSet6import requests7from .data import SmartAnswer8import settings9logger = logging.getLogger(__name__)10class PerformancePlatform(object):11 """12 Handles GETting and POSTing data to and from the Performance Platform.13 This class uses the PerformancePlatform Client, which will retry14 handling GET and POST requests up to five times, if their status15 codes are 502 or 503. If they still don't succeed, the client16 raises an exception that is not handled by us.17 """18 date_format = "%Y-%m-%dT00:00:00Z"19 def __init__(self, pp_token, start_date, end_date):20 self.pp_token = pp_token21 # Format dates here so that they won't be accidentally used as22 # non-midnight datetimes elsewhere in the class:23 self.start_date = start_date.strftime(self.date_format)24 self.end_date = end_date.strftime(self.date_format)25 def get_problem_report_counts(self):26 logger.info('Getting problem report counts')27 results_by_letter = [self._get_problem_report_counts_for_paths_starting_with('/' + letter)28 for letter in string.lowercase]29 all_results = list(itertools.chain(*results_by_letter))30 return {result["pagePath"].encode('utf-8'): result["total:sum"]31 for result in all_results}32 def get_search_counts(self):33 logger.info('Getting search counts')34 results_by_letter = [self._get_search_counts_for_paths_starting_with('/' + letter)35 for letter in string.lowercase]36 all_results = list(itertools.chain(*results_by_letter))37 return {result["pagePath"].encode('utf-8'): result["searchUniques:sum"]38 for result in all_results}39 def get_unique_pageviews(self, paths):40 logger.info('Getting pageview counts')41 return {path: self.get_unique_pageviews_for_path(path) for path in paths}42 def get_unique_pageviews_for_path(self, path):43 data = self._get_pp_data('page-statistics', 'uniquePageviews:sum',44 filter_by=path)45 if data and data[0]['uniquePageviews:sum']:46 return int(data[0]['uniquePageviews:sum'])47 def save_aggregated_results(self, results):48 data_set = DataSet.from_group_and_type(settings.DATA_DOMAIN,49 settings.DATA_GROUP,50 settings.RESULTS_DATASET,51 token=self.pp_token)52 enriched_results = [self._enrich_mandatory_pp_fields(result)53 for result in results]54 logger.info('Posting data to Performance Platform')55 data_set.post(enriched_results)56 def _get_problem_report_counts_for_paths_starting_with(self, path_prefix):57 return self._get_pp_data('page-contacts', 'total:sum',58 filter_by_prefix=path_prefix)59 def _get_search_counts_for_paths_starting_with(self, path_prefix):60 return self._get_pp_data('search-terms', 'searchUniques:sum',61 filter_by_prefix=path_prefix)62 def _enrich_mandatory_pp_fields(self, result):63 enriched_result = copy.copy(result.as_dict())64 enriched_result['_timestamp'] = self.end_date65 enriched_result['_start_at'] = self.start_date66 enriched_result['_end_at'] = self.end_date67 return enriched_result68 def _get_pp_data(self, dataset_name, value,69 filter_by=None, filter_by_prefix=None):70 dataset = DataSet.from_group_and_type(settings.DATA_DOMAIN,71 settings.DATA_GROUP,72 dataset_name)73 query_parameters = {74 'group_by': 'pagePath',75 'period': 'day',76 'start_at': self.start_date,77 'end_at': self.end_date,78 'collect': value,79 }80 if filter_by:81 query_parameters['filter_by'] = 'pagePath:' + filter_by82 elif filter_by_prefix:83 query_parameters['filter_by_prefix'] = 'pagePath:' + filter_by_prefix84 logger.debug('Getting {0} data with params {1}'.format(dataset_name, query_parameters))85 json_data = dataset.get(query_parameters)86 if 'data' in json_data:87 return json_data['data']88 else:89 return []90class GOVUK(object):91 def get_smart_answers(self):92 """Get all smart answers, from the Search API."""93 logger.info('Getting smart answers')94 smart_answers = []95 url = 'https://www.gov.uk/api/search.json'96 url += '?filter_format=smart-answer'97 url += '&filter_format=simple_smart_answer'98 url += '&start=0&count=1000&fields=link'99 try:100 r = requests.get(url)101 if r.status_code == 200:102 results = r.json()['results']103 return [SmartAnswer(result['link'].encode('utf-8')) for result in results]104 else:105 logger.error('Received %d status code when getting smartanswers from %s',106 r.status_code, url)107 except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e:...

Full Screen

Full Screen

practice 03.py

Source:practice 03.py Github

copy

Full Screen

...7 'cherry',8 'charlie',9]1011def filter_by_prefix(words, prefix):12 '''13 prefix로 시작하는 word를 린턴합니다. 1415 >>> filter_by_prefix(words, 'a')16 'apple'17 '''18 19 # 아래 코드를 작성하세요.20 21 22 return [i for i in words if i.startswith(prefix)]232425# 아래 주석을 해제하고 결과를 확인해보세요. 26a_words = filter_by_prefix(words, 'a')27print(a_words)28293031'''32한 줄 명령어로 데이터 다루기33파이썬의 가장 큰 장점 중 하나는 간결한 코드입니다. for문을 리스트 안에 입력하면 새로운 리스트를 코드 한 줄로 간결하게 생성할 수 있습니다. 아래의 두 코드는 동일하게 작동합니다.34'''3536'''37데이터 분석에 응용하기38None을 삭제하고 단어 모음 words에서 prefix로 시작하는 단어만 리턴하는 filter_by_prefix 함수를 완성하세요. ...

Full Screen

Full Screen

canonical_solution_29.py

Source:canonical_solution_29.py Github

copy

Full Screen

1from typing import List234def filter_by_prefix(strings: List[str], prefix: str) -> List[str]:5 """ Filter an input list of strings only for ones that start with a given prefix.6 >>> filter_by_prefix([], 'a')7 []8 >>> filter_by_prefix(['abc', 'bcd', 'cde', 'array'], 'a')9 ['abc', 'array']10 """ ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful