Best Python code snippet using avocado_python
app.py
Source:app.py
...4from tabulate import tabulate5app = Flask(__name__)6number_stations = pd.read_csv("./data/number_stations.csv")7# Print tabular data8def tabular_output(i):9 print(tabulate(i, tablefmt='simple', headers=["ID", "Name", "Country", "Active Counterparts", "Inactive Counterparts", "Nickname", "Status", "Frequency", "Voice", "Emission Mode", "Location"], showindex='never')) 10# List all stations11@app.route('/')12def index():13 f = number_stations.to_json()14 return json.loads(f)15# List all stations under the column Name16@app.route('/station_names')17def station_names():18 # Filter the DataFrame columns to retrieve all stations under 'Name' column19 st_name = number_stations['Name']20 # If the DataFrame returns a response, convert the Series to a JSON string21 f = st_name.to_json()22 # Then convert the JSON string to a dict to properly format it when sending the response to the client23 return json.loads(f)24# Check for active stations25@app.route('/is_active_station')26def is_active_station():27 # Pass the parameter from the URL and check if it matches against an active station28 active_df = number_stations[number_stations['Status'] == 'Active']29 # Use tabulate to print the response to the terminal30 tabular_output(active_df)31 r = active_df.to_json()32 return json.loads(r)33# Check for inactive stations34@app.route('/is_inactive_station')35def is_inactive_station():36 # Pass the parameter from the URL and check if it matches against an inactive station37 inactive_df = number_stations[number_stations['Status'] == 'Inactive']38 # Use tabulate to print the response to the terminal39 tabular_output(inactive_df)40 r = inactive_df.to_json()41 return json.loads(r)42# Filter by station names43@app.route('/filter_station_names/<name>')44def filer_station_names(name):45 if name is None:46 return jsonify({ 'error': 'Station name cannot be blank' })47 # Pass the parameter from the URL and check if it matches against a known station name48 f_name = number_stations[number_stations['Name'] == name]49 # Use tabulate to print the response to the terminal50 tabular_output(f_name)51 # If the DataFrame returns empty, send an error back to the client52 if f_name.empty:53 return jsonify({ 'error': 'That station does not exist'})54 # If the DataFrame returns a response, convert the Series to a JSON string55 r = f_name.to_json()56 # Then convert the JSON string to a dict to properly format it when sending the response to the client57 return json.loads(r)58# Filter by station nicknames59@app.route('/filter_station_nickname/<nickname>')60def filer_station_nickname(nickname):61 if nickname is None:62 return jsonify({ 'error': 'Station nickname cannot be blank' })63 # Pass the parameter from the URL and check if it matches against a known station nickname64 f_nickname = number_stations[number_stations['Nickname'].str.contains(nickname)]65 # Use tabulate to print the response to the terminal66 tabular_output(f_nickname)67 # If the DataFrame returns empty, send an error back to the client68 if f_nickname.empty:69 return jsonify({ 'error': 'That station does not exist'})70 # If the DataFrame returns a response, convert the Series to a JSON string71 r = f_nickname.to_json()72 # Then convert the JSON string to a dict to properly format it when sending the response to the client73 return json.loads(r)74# Filter by station id's75@app.route('/filter_by_id/<id>')76def filter_by_id(id):77 if id is None:78 return jsonify({ 'error': 'ID cannot be empty' })79 # Pass the parameter from the URL and check if it matches against a known station id80 f_id = number_stations[number_stations['ID'] == id]81 # Use tabulate to print the response to the terminal82 tabular_output(f_id)83 # If the DataFrame returns empty, send an error back to the client84 if f_id.empty:85 return jsonify({ 'error': 'That ID does not exist'})86 # If the DataFrame returns a response, convert the Series to a JSON string87 r = f_id.to_json()88 # Then convert the JSON string to a dict to properly format it when sending the response to the client89 return json.loads(r)90# Filter by station locations91@app.route('/filter_by_location/<loc>')92def filter_by_location(loc):93 if loc is None:94 return jsonify({ 'error': 'Location cannot be empty' })95 # Pass the parameter from the URL and check if it matches against a known location - 'na=False' ignores any possibly empty values in the column to avoid throwing an error96 f_loc = number_stations[number_stations['Location'].str.contains(loc, na=False)]97 # Use tabulate to print the response to the terminal98 tabular_output(f_loc)99 # If the DataFrame returns empty, send an error back to the client100 if f_loc.empty:101 return jsonify({ 'error': 'That location does not exist'})102 # If the DataFrame returns a response, convert the Series to a JSON string103 r = f_loc.to_json()104 # Then convert the JSON string to a dict to properly format it when sending the response to the client105 return json.loads(r)106# Catch all HTTP 404's and return the below JSON message107@app.errorhandler(404)108def route_not_found(e):...
preprocess.py
Source:preprocess.py
1import os2from pathlib import Path3import numpy as np4import pandas as pd5import torch6class TabularData(object):7 r"""Object to store train + testing data for ML runs8 """9 def __init__(10 self,11 X_train: np.array,12 X_test: np.array,13 y_train: np.array,14 y_test: np.array15 ):16 self.X_train = pd.DataFrame(X_train)17 self.X_test = pd.DataFrame(X_test)18 self.y_train = pd.DataFrame(y_train)19 self.y_test = pd.DataFrame(y_test)20 self.save()21 def save(self):22 os.makedirs('output/tabular_output', exist_ok=True)23 self.X_train.to_csv('output/tabular_output/X_train.csv')24 self.y_train.to_csv('output/tabular_output/y_train.csv')25 self.X_test.to_csv('output/tabular_output/X_test.csv')26 self.y_test.to_csv('output/tabular_output/y_test.csv')27class GraphsToTabularConverter(object):28 def __init__(self, data_dir):29 self.data_dir = data_dir30 self.train_files = Path(data_dir).joinpath('train_files.csv')31 self.test_files = Path(data_dir).joinpath('test_files.csv')32 self.tabular_data: TabularData = TabularData([], [], [], [])33 self.execute()34 def execute(self):35 train_df = pd.read_csv(self.train_files)36 train_df['x,y'] = train_df['filename'].apply(self.graph_to_df)37 test_df = pd.read_csv(self.test_files)38 test_df['x,y'] = test_df['filename'].apply(self.graph_to_df)39 X_train = self.x_list_to_numpy(train_df)40 y_train = self.y_list_to_numpy(train_df)41 X_test = self.x_list_to_numpy(test_df)42 y_test = self.y_list_to_numpy(test_df)43 self.tabular_data = TabularData(X_train, X_test, y_train, y_test)44 @staticmethod45 def graph_to_df(file):46 graph = torch.load(file)47 x = graph.x48 y = graph.y49 return [x, y]50 @staticmethod51 def x_list_to_numpy(data_df):52 data = data_df['x,y'].apply(lambda x: x[0]).tolist()53 data = np.array([[__.numpy() for __ in _] for _ in np.array(data).T])54 n_pts = data.shape[0]55 n_nodes = data.shape[1]56 data = data.reshape(n_pts, n_nodes)57 return data58 @staticmethod59 def y_list_to_numpy(data_df):60 y_list = data_df['x,y'].apply(lambda x: x[1]).tolist()61 y_np = np.array([y[0].numpy() for y in np.array(y_list).T])...
test_utils_astring.py
Source:test_utils_astring.py
1import unittest2from avocado.utils import astring3class AstringUtilsTest(unittest.TestCase):4 def test_tabular_output(self):5 self.assertEqual(astring.tabular_output([]), "")6 self.assertEqual(astring.tabular_output([],7 header=('C1', 'C2', 'C3')),8 "C1 C2 C3")9 self.assertEqual(astring.tabular_output([['v11', 'v12', 'v13']]),10 "v11 v12 v13")11 self.assertEqual(astring.tabular_output([['v11', 'v12', 'v13'],12 ['v21', 'v22', 'v23']],13 header=('C1', 'C2', 'C3')),14 "C1 C2 C3" + "\n" +15 "v11 v12 v13" + "\n" +16 "v21 v22 v23")17 self.assertEqual(astring.tabular_output([['v11', 'v12', ''],18 ['v21', 'v22', 'v23']],19 header=('C1', 'C2', 'C3')),20 "C1 C2 C3" + "\n" +21 "v11 v12 " + "\n" +22 "v21 v22 v23")23 self.assertEqual(astring.tabular_output([['v11', 'v12', ''],24 ['v21', 'v22', 'v23']],25 header=('C1', 'C2', 'C3'),26 strip=True),27 "C1 C2 C3" + "\n" +28 "v11 v12" + "\n" +29 "v21 v22 v23")30 self.assertEqual(astring.tabular_output([['v11', 'v12', ''],31 ['v2100', 'v22', 'v23'],32 ['v31', 'v320', 'v33']],33 header=('C1', 'C02', 'COL3')),34 "C1 C02 COL3" + "\n" +35 "v11 v12 " + "\n" +36 "v2100 v22 v23" + "\n" +37 "v31 v320 v33")38if __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!!