Best Python code snippet using lisa_python
speed_review.py
Source:speed_review.py
1import unittest2from itertools import groupby34import pandas as pd5import numpy as np6789class MyTestCase(unittest.TestCase):1011 df = pd.read_csv("Dogs_short.csv", parse_dates=[["Date","Time"]], dayfirst=True)12 df.drop(df.index[df.SP.eq(0)], inplace=True)1314 df["Fin"] = df["Fin"].where(df["Fin"].eq("1"), 0).astype(int)15 df.sort_values(by="Date_Time", inplace=True)16 df["Date_Time_dt"] = df["Date_Time"].dt.date17 df = df.drop_duplicates(subset=["Dog name", "Date_Time_dt"])18 df.reset_index(inplace=True, drop=True)1920 # 1-task21 #@unittest.skip("demonstrating skipping")22 def test_convo_group_mean(self):23 cmg = convo_mean_group(self.df, "SP", 5, "Dog name")24 normal_rolling = self.df.groupby(by="Dog name")["SP"].rolling(5, min_periods=1).mean()25 normal_rolling.sort_index(level=1, inplace=True)26 normal_rolling.index = normal_rolling.index.droplevel(0)27 cmg.name = normal_rolling.name28 pd.testing.assert_series_equal(cmg, normal_rolling)2930 # 2-task31 #@unittest.skip("demonstrating skipping")32 def test_races_since_win(self):33 self.df["since_last_win"] = since_last_win(self.df, "Dog name")34 last_value = self.df.loc[self.df["Dog name"].eq("Foxwood Boom"), "Fin"][::-1].cumsum().eq(0).sum() - 135 self.assertEqual(last_value, self.df.loc[self.df["Dog name"].eq("Foxwood Boom"), "since_last_win"].iloc[-1])3637 # 3-task38 #@unittest.skip("demonstrating skipping")39 def test_insert_historical(self):40 c = self.df.groupby(by="Dog name")["SP"].transform(lambda x: x.expanding().mean().shift())41 self.df["expanding_SP"] = self.df.groupby(by="Dog name")["SP"].transform(lambda x: x.expanding().mean())42 until_df = self.df.loc[:, ["Dog name", "expanding_SP", "Date_Time"]]43 self.df.drop("expanding_SP", axis=1, inplace=True)44 self.df = insert_historical_attrs_groupby(self.df, until_df, ["Dog name"], ["expanding_SP"])4546 pd.testing.assert_series_equal(self.df["expanding_SP"], c, check_names=False)4748def since_last_win(df, group_attr):49 return df.groupby(group_attr)["Fin"].transform(lambda x: x.groupby(x.cumsum()).cumcount().shift())5051def convo_mean_group(df, attr, window_size, group_attr):52 groups = df.groupby(group_attr)[attr]53 s = [[],[]]54 for i, grp in groups:55 s[1].extend(grp.index)56 c = np.convolve(grp, np.ones(window_size))[:len(grp)]57 divisor = np.ones(len(grp))*window_size58 divisor[:min(len(grp),window_size)] = np.arange(min(len(grp),window_size)) +159 s[0].extend(c/divisor)60 return pd.Series(s[0], index=s[1]).sort_index()6162def insert_historical_attrs_groupby(df, historical_df, merge_variables, new_variables):63 interim_df = df.groupby(merge_variables + [df["Date_Time"].dt.normalize()]).size()64 interim_df = interim_df.reset_index().iloc[:, :-1]6566 interim_df_hist = historical_df.groupby(merge_variables + [df["Date_Time"].dt.normalize()])[new_variables].last().reset_index()6768 interim_df = interim_df.merge(interim_df_hist, on=merge_variables, suffixes=(None, "_hist"))69 interim_df = interim_df.loc[interim_df["Date_Time"].gt(interim_df["Date_Time_hist"]),:].drop_duplicates(keep="last", subset=merge_variables + ["Date_Time"])7071 return df.merge(interim_df, how="left", left_on=merge_variables + [df["Date_Time"].dt.normalize()], right_on= merge_variables + ["Date_Time"])727374if __name__ == '__main__':
...
runner_meta_classs.py
Source:runner_meta_classs.py
...21 """22def {{ test_step_func_name }}(self, step): 23 # override variables24 # step variables > extracted variables from previous steps25 step.variables = merge_variables(step.variables, self.extracted_variables)26 # step variables > testcase config variables27 step.variables = merge_variables(step.variables, self._config.variables)28 # parse variables29 step.variables = parse_variables_mapping(30 step.variables, self._project_meta.functions31 )32 # run step33 # with allure.step(f"step{step.idx}: {step.name}"):34 # allure.dynamic.title(f"step{step.idx}: {step.name}")35 allure.dynamic.description(step.description or step.name)36 step_data = self.run_step(step)37 extract_mapping = step_data.export_vars38 # save extracted variables to session variables39 self.extracted_variables.update(extract_mapping)40"""41)...
PasswordGenerator.py
Source:PasswordGenerator.py
1""" Password Generator"""2import sys3import random4import string5def main():6 try:7 password_length = int(input("Insert the length of the password: "))8 if password_length > 0:9 password_generator(password_length)10 print(password_generator(password_length))11 else:12 print("Invalid input. Try again. \n")13 main()14 except ValueError:15 print("Invalid input. Try again. \n")16 main()17def password_generator(password_length):18 # variables for the password19 lowercase = string.ascii_lowercase20 uppercase = string.ascii_uppercase21 numbers = string.digits22 symbols = string.punctuation23 # temporarily stores a random combination24 merge_variables = lowercase + uppercase + numbers + symbols25 password_proto = random.sample(merge_variables, password_length)26 # merges the combination into a string27 password_final = "".join(password_proto)28 return password_final29# Press the green button in the gutter to run the script.30if __name__ == '__main__':...
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!!