Best Python code snippet using prospector_python
helpers.py
Source: helpers.py
...137 line = line.replace(r[0], r[1])138 lines.append(line)139 140 return lines141def get_summary_information():142 """143 get_summary_information Retrieves all strings needed to fill summary.tex and title.tex144 :return: A dictionary with all strings needed to replace in the tex files.145 """ 146 if not check_file(SUMMARY_INFORMATION):147 print("I can't find summary_information.conf. Make sure it is in the source folder.")148 exit(1)149 150 config = configparser.ConfigParser()151 config.read(SUMMARY_INFORMATION)152 153 summary : dict[str, str] = {}154 155 # Copy to dictionary...
lambda_function.py
Source: lambda_function.py
...55 _csv = 'summaries_information/summary_information.csv'56 df = pd.read_csv(_csv, delimiter=',', skip_blank_lines=True, encoding='utf8')57 df.rename(columns={"Id": "number", "Date": "date", "Transaction": "amount"}, inplace=True)58 return df59def get_summary_information(account: Account, df: pd.DataFrame) -> dict:60 """61 Generates the summary information62 Args:63 account (Account): Account to use.64 df (pd.DataFrame): Data frame to extract the summary information65 Returns:66 dict: Summary information.67 Examples:68 {'username': 'Edgar de la Cruz', 'total_balance': 39.74, 'average_credit_amount': 35.25,69 'average_debit_amount': -15.38, 'month_transactions': {'July': 2, 'August': 2}}70 """71 logger.info('Summary information')72 total_balance = df['amount'].sum().round(2)73 average_credit_amount = df[df['amount'] > 0]['amount'].mean().round(2)74 average_debit_amount = df[df['amount'] < 0]['amount'].mean().round(2)75 df['formatted_date'] = pd.to_datetime(df['date'], format='%m/%d')76 month_transactions = df.groupby(pd.Grouper(key='formatted_date', freq='M'))['amount'].count()77 month_transactions.index = month_transactions.index.strftime('%B')78 logger.info(f'Total balance is {total_balance}')79 logger.info(f'Average credit amount: {average_credit_amount}')80 logger.info(f'Average debit amount: {average_debit_amount}')81 for month, total in month_transactions.iteritems():82 logger.info(f'Number of transactions in {month}: {total}')83 summary_information = {84 "username": f"{account.name} {account.paternal_surname}",85 "total_balance": total_balance,86 "average_credit_amount": average_credit_amount,87 "average_debit_amount": average_debit_amount,88 "month_transactions": month_transactions.to_dict(),89 }90 return summary_information91def save_db(account: Account, df: pd.DataFrame) -> bool:92 """93 Save the account transactions94 Args:95 account (Account): Account record to save the transactions96 df (pd.DataFrame): Data frame from csv with the transactions97 Returns:98 bool: True for success, False otherwise.99 Returns:100 """101 logger.info('Saving transactions...')102 try:103 df['account'] = account.id104 transactions = df[['number', 'date', 'amount', 'account']].to_dict(orient='records')105 Transaction.insert_many(transactions).execute()106 return True107 except Exception as e:108 logger.info(f'An error occurred while saving the transactions: {str(e)}')109 return False110def send_mail(summary_information: dict) -> bool:111 """112 Sends an email with the summary information113 Args:114 summary_information (dict): summary information.115 {'username': 'Edgar de la Cruz', 'total_balance': 39.74, 'average_credit_amount': 35.25,116 'average_debit_amount': -15.38, 'month_transactions': {'July': 2, 'August': 2}}117 Returns:118 bool: True for success, False otherwise.119 """120 logger.info('Sending email...')121 message = Mail(122 from_email=FROM_EMAIL,123 to_emails=TO_EMAIL124 )125 message.dynamic_template_data = summary_information126 message.template_id = SENDGRID_SUMMARY_TEMPLATE_ID127 try:128 sg = SendGridAPIClient(SENDGRID_API_KEY)129 response = sg.send(message)130 logger.info(response.status_code)131 logger.info(response.body)132 logger.info(response.headers)133 return True134 except Exception as e:135 logger.info(f'An error occurred while sending the summary information: {str(e)}')136 return False137def get_account() -> Account:138 """139 Gets or creates an account with the email assigned to the environment variable TO_EMAIL140 Returns:141 Account: Account to use.142 """143 logger.info('Getting the account...')144 account, created = Account.get_or_create(145 email=TO_EMAIL,146 defaults={'name': 'Edgar', 'paternal_surname': 'de la Cruz', 'maternal_surname': 'Vasconcelos'}147 )148 return account149def lambda_handler(event=None, context=None) -> dict:150 account = get_account()151 df = read_csv()152 summary_information = get_summary_information(account, df)153 save_db(account, df)154 send_mail(summary_information)155 return {156 "message": "Processed information"157 }158if __name__ == '__main__':...
test_site_information.py
Source: test_site_information.py
...15def test_set_sites_information(site_info_handler: BinInformationHandler):16 site_info_handler.set_sites_information(BIN_TABLE)17 assert site_info_handler.get_num_sites() == 118def test_no_test_result_stored(site_info_handler: BinInformationHandler):19 assert len(site_info_handler.get_summary_information({})) == 020def test_store_test_result(site_info_handler: BinInformationHandler):21 site_info_handler.set_sites_information(BIN_TABLE)...
Check out the latest blogs from LambdaTest on this topic:
“Test frequently and early.” If you’ve been following my testing agenda, you’re probably sick of hearing me repeat that. However, it is making sense that if your tests detect an issue soon after it occurs, it will be easier to resolve. This is one of the guiding concepts that makes continuous integration such an effective method. I’ve encountered several teams who have a lot of automated tests but don’t use them as part of a continuous integration approach. There are frequently various reasons why the team believes these tests cannot be used with continuous integration. Perhaps the tests take too long to run, or they are not dependable enough to provide correct results on their own, necessitating human interpretation.
As a developer, checking the cross browser compatibility of your CSS properties is of utmost importance when building your website. I have often found myself excited to use a CSS feature only to discover that it’s still not supported on all browsers. Even if it is supported, the feature might be experimental and not work consistently across all browsers. Ask any front-end developer about using a CSS feature whose support is still in the experimental phase in most prominent web browsers. ????
Have you ever visited a website that only has plain text and images? Most probably, no. It’s because such websites do not exist now. But there was a time when websites only had plain text and images with almost no styling. For the longest time, websites did not focus on user experience. For instance, this is how eBay’s homepage looked in 1999.
Recently, I was going through some of the design patterns in Java by reading the book Head First Design Patterns by Eric Freeman, Elisabeth Robson, Bert Bates, and Kathy Sierra.
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!