Best Python code snippet using slash
nsx_ospf.py
Source:nsx_ospf.py
...239 changed = True240 if changed:241 current_config['routing']['ospf']['ospfInterfaces'] = {'ospfInterface': new_area_map}242 return changed, current_config243def get_current_config(client_session, edge_id):244 response = client_session.read('routingConfig', uri_parameters={'edgeId': edge_id})245 return response['body']246def update_config(client_session, current_config, edge_id):247 client_session.update('routingConfig', uri_parameters={'edgeId': edge_id},248 request_body_dict=current_config)249def reset_config(client_session, edge_id):250 client_session.delete('routingOSPF', uri_parameters={'edgeId': edge_id})251def main():252 module = AnsibleModule(253 argument_spec=dict(254 state=dict(default='present', choices=['present', 'absent']),255 nsxmanager_spec=dict(required=True, no_log=True, type='dict'),256 edge_name=dict(required=True, type='str'),257 router_id=dict(required=True, type='str'),258 graceful_restart=dict(default=True, type='bool'),259 default_originate=dict(default=False, type='bool'),260 protocol_address=dict(type='str'),261 forwarding_address=dict(type='str'),262 logging=dict(default=False, type='bool'),263 log_level=dict(default='info', choices=['debug', 'info', 'notice', 'warning', 'error', 'critical',264 'alert', 'emergency'], type='str'),265 areas=dict(type='list'),266 area_map=dict(type='list')267 ),268 supports_check_mode=False269 )270 from nsxramlclient.client import NsxClient271 client_session = NsxClient(module.params['nsxmanager_spec']['raml_file'], module.params['nsxmanager_spec']['host'],272 module.params['nsxmanager_spec']['user'], module.params['nsxmanager_spec']['password'])273 edge_id, edge_params = get_edge(client_session, module.params['edge_name'])274 if not edge_id:275 module.fail_json(msg='could not find Edge with name {}'.format(module.params['edge_name']))276 current_config = get_current_config(client_session, edge_id)277 if module.params['state'] == 'absent' and check_ospf_state(current_config):278 reset_config(client_session, edge_id)279 module.exit_json(changed=True, current_config=None)280 elif module.params['state'] == 'absent' and not check_ospf_state(current_config):281 module.exit_json(changed=False, current_config=None)282 changed_state, current_config = set_ospf_state(current_config)283 changed_rtid, current_config = check_router_id(current_config, module.params['router_id'])284 changed_opt, current_config = check_ospf_options(current_config, module.params['graceful_restart'],285 module.params['default_originate'],286 module.params['forwarding_address'],287 module.params['protocol_address'])288 valid, msg, area_map = normalize_areas(module.params['areas'])289 if not valid:290 module.fail_json(msg=msg)...
ConfigScreen.py
Source:ConfigScreen.py
1import time2import logging3import threading4from functools import partial5import json6from datetime import timedelta 7import csv8import datetime9from tkinter.filedialog import asksaveasfile10from tkinter import Tk11import os 12from os.path import expanduser13from BackgroundTimer import BackgroundTimer14from Plot2D import Plot2D15import numpy as np16from numpy import pi, sin, cos, tan17from PyQt5 import QtGui18class ConfigScreen():19 def __init__(self, View, config):20 self.View = View21 self.current_config = config22 # define the basic visual objects23 self.config_sliders = (24 View.window.cost_kwh,25 View.window.cost_m3,26 View.window.notification_day, 27 View.window.report_rate28 )29 self.config_sliders_labels = (30 View.window.cost_kwh_label,31 View.window.cost_m3_label,32 View.window.notification_day_label, 33 View.window.report_rate_label34 )35 self.config_sliders_names = (36 "cost_kwh",37 "cost_m3",38 "notification_day",39 "report_rate"40 )41 self.labels = (42 "Cost of kwh in COP: ",43 "Cost of m^3 of water in COP: ",44 "Notification day: ",45 "Report data rate in seconds: "46 )47 self.config_check_box = (48 View.window.email_notifications,49 View.window.remote_mode_button50 )51 self.config_check_box_names = (52 "email_notifications",53 "remote_mode"54 )55 # load the configuration from the json file56 self.load_config_data()57 # relate the handler for sliders and the check boxes58 for index, slider in enumerate(self.config_sliders):59 slider.valueChanged.connect(partial(self.on_slider_changed, index))60 61 for index, check_box in enumerate(self.config_check_box):62 check_box.clicked.connect(partial(self.on_check_changed, index))63 # connect all the buttons to the clicked handler:64 View.window.default_config.clicked.connect(self.default_config)65 View.window.save_config.clicked.connect(self.save_config)66 def change_db_mode(self):67 print("change_mode_check pressed")68 if self.View.window.remote_mode_button.isChecked():69 self.View.window.remote_mode_button.setChecked(True)70 self.View.controller.try_connection = True71 else:72 self.View.window.remote_mode_button.setChecked(False)73 self.View.controller.try_connection = False74 def load_config_data(self):75 """76 # load the configuration file:77 try:78 # read and get the configuration from the file79 with open("./config.json") as json_data_file:80 self.current_config = json.load(json_data_file)81 logging.debug(self.current_config) # now this becomes a dictionary with unicode string formats82 except Exception as e:83 logging.debug("generic error wile reloading the configuration file: ")84 print(e)85 """86 # set all visual objecs to the loaded values87 self.View.window.cost_kwh.setValue(self.current_config["cost_kwh"])88 self.config_sliders_labels[0].setText(self.labels[0]+str(self.current_config["cost_kwh"]))89 self.View.window.cost_m3.setValue(self.current_config["cost_m3"])90 self.config_sliders_labels[1].setText(self.labels[1]+str(self.current_config["cost_m3"]))91 self.View.window.notification_day.setValue(self.current_config["notification_day"])92 self.config_sliders_labels[2].setText(self.labels[2]+str(self.current_config["notification_day"]))93 self.View.window.report_rate.setValue(self.current_config["report_rate"])94 self.config_sliders_labels[3].setText(self.labels[3]+str(self.current_config["report_rate"]))95 96 if self.current_config["email_notifications"] == "on": self.config_check_box[0].setChecked(True)97 else: self.config_check_box[0].setChecked(False)98 if self.current_config["remote_mode"] == "on": self.config_check_box[1].setChecked(True)99 else: self.config_check_box[1].setChecked(False)100 def on_slider_changed(self, index, new_value):101 #current_value = self.sampleRate_sliders[index].value() # this is a diferent way to get the slider value102 self.config_sliders_labels[index].setText(self.labels[index]+str(new_value))103 self.current_config[self.config_sliders_names[index]] = new_value104 def on_check_changed(self, index):105 if self.config_check_box[index].isChecked():106 self.current_config[self.config_check_box_names[index]] = "on"107 else:108 self.current_config[self.config_check_box_names[index]] = "off"109 if self.config_check_box[index] == self.View.window.remote_mode_button:110 self.change_db_mode()111 def save_config(self):112 113 with open('./config.json', 'w') as outfile:114 json.dump(self.current_config, outfile)115 #display a message116 msgBox = QtGui.QMessageBox()117 msgBox.setText("Configuration correctly saved")118 msgBox.setWindowTitle("¡Hi!")119 ret = msgBox.exec_() 120 def default_config(self):121 122 # ram update123 self.current_config["cost_kwh"] = 500124 self.current_config["cost_m3"] = 300125 self.current_config["notification_day"] = 15 126 self.current_config["report_rate"] = 10127 self.current_config["email_notifications"] = "on"128 self.current_config["remote_mode"] = "off"129 # self.current_config["serial_number"] = 1000000000130 self.current_config["device_names"] = [131 132 # potencia133 "Energy Metter SDL",134 "Energy Metter SDL",135 "Energy Metter SDL",136 "Energy Metter SDL",137 "Energy Metter SDL",138 "Energy Metter SDL",139 # fluido140 "Flow Metter SDL",141 "Flow Metter SDL",142 # Confort143 "Confort Metter SDL",144 "Confort Metter SDL",145 "Confort Metter SDL",146 "Confort Metter SDL",147 "Confort Metter SDL",148 "Confort Metter SDL",149 "Confort Metter SDL",150 "Confort Metter SDL",151 "Confort Metter SDL",152 "Confort Metter SDL"153 ]154 self.current_config["data_types"] = [155 156 # potencia157 "potencia acumulada",158 "corriente instantenea",159 "factor de potencia",160 "potencia acumulada",161 "corriente instantenea",162 "factor de potencia",163 # fluido164 "fluido consumido",165 "flujo instantaneo",166 # Confort167 "temperatura",168 "humedad",169 "temperatura",170 "humedad",171 "temperatura",172 "humedad",173 "temperatura",174 "humedad",175 "temperatura",176 "humedad"177 ]178 self.current_config["serial_numbers"] = [179 180 # potencia181 1,182 1,183 1,184 2,185 2,186 2,187 188 # fluido189 1,190 1,191 # Confort192 1,193 1,194 2,195 2,196 3,197 3,198 4,199 4,200 5,201 5202 ]203 self.current_config["xbee_names"] = [204 205 "EM_1",206 "EM_1",207 "EM_1",208 "EM_2",209 "EM_2",210 "EM_2",211 "WM",212 "WM",213 "CM_1",214 "CM_1",215 "CM_2",216 "CM_2",217 "CM_3",218 "CM_3",219 "CM_4",220 "CM_4",221 "CM_5",222 "CM_5"223 ] 224 self.current_config["xbee_headers"] = [225 226 bytearray("E", "utf-8"),227 bytearray("I", "utf-8"),228 bytearray("FP", "utf-8"),229 bytearray("E", "utf-8"),230 bytearray("I", "utf-8"),231 bytearray("FP", "utf-8"),232 bytearray("WA", "utf-8"),233 bytearray("F", "utf-8"),234 bytearray("T", "utf-8"),235 bytearray("H", "utf-8"),236 bytearray("T", "utf-8"),237 bytearray("H", "utf-8"),238 bytearray("T", "utf-8"),239 bytearray("H", "utf-8"),240 bytearray("T", "utf-8"),241 bytearray("H", "utf-8"),242 bytearray("T", "utf-8"),243 bytearray("H", "utf-8")244 ]245 246 self.current_config["control__device_names"] = [247 "Control grid SDL",248 "Control grid SDL",249 "Control grid SDL",250 "Control grid SDL",251 "Control grid SDL",252 "Control grid SDL",253 "Control grid SDL",254 "Control grid SDL",255 "Control grid SDL",256 "Control grid SDL",257 "Control grid SDL",258 "Control grid SDL",259 "Control grid SDL",260 "Control grid SDL",261 "Control grid SDL",262 "Control grid SDL"263 ]264 self.current_config["control__serial_numbers"] = [265 1,266 1,267 1,268 1,269 2,270 2,271 2,272 2,273 3,274 3,275 3,276 3,277 4,278 4,279 4,280 4281 ]282 self.current_config["control__data_types"] = [283 "circuit1",284 "circuit2",285 "circuit3",286 "circuit4",287 "circuit1",288 "circuit2",289 "circuit3",290 "circuit4",291 "circuit1",292 "circuit2",293 "circuit3",294 "circuit4",295 "circuit1",296 "circuit2",297 "circuit3",298 "circuit4"299 ]300 #file update301 self.save_config()302 #visualy update303 self.load_config_data()304 #display a message305 #display a message306 msgBox = QtGui.QMessageBox()307 msgBox.setText("Default configuration restored")308 msgBox.setWindowTitle("¡Hi!")...
whos_oncall.py
Source:whos_oncall.py
1import logging2import os3import time4from dotenv import load_dotenv5import boto36import json7import re8load_dotenv()9logging.basicConfig(level=logging.INFO)10def get_current_oncall_user():11 config = _get_oncall_config()12 return config['current_config']['oncall_user']13def set_current_oncall_user(user_id, actor_id):14 config = _get_oncall_config()15 assert user_id in config['available_users']['users']16 config['current_config']['oncall_user'] = config['available_users']['users'][user_id]17 _set_oncall_config(config, actor_id)18def get_current_pager_phone():19 config = _get_oncall_config()20 return config['current_config']['pager_phone']21def get_current_from_phone():22 config = _get_oncall_config()23 return config['current_config']['from_phone']24def get_current_from_email():25 config = _get_oncall_config()26 return config['current_config']['mail_settings']['from_email']27def get_current_to_email():28 config = _get_oncall_config()29 return config['current_config']['mail_settings']['to_email']30def get_current_mail_password():31 config = _get_oncall_config()32 return config['current_config']['mail_settings']['mail_password']33def get_current_mail_port():34 config = _get_oncall_config()35 return config['current_config']['mail_settings']['mail_port']36def get_current_mail_server():37 config = _get_oncall_config()38 return config['current_config']['mail_settings']['mail_server']39def get_current_mail_use_tls():40 config = _get_oncall_config()41 return config['current_config']['mail_settings']['mail_use_tls']42def get_current_mail_username():43 config = _get_oncall_config()44 return config['current_config']['mail_settings']['mail_username']45def get_current_session_lifetime():46 config = _get_oncall_config()47 return config['current_config']['session_lifetime']48def get_available_oncall_users():49 config = _get_oncall_config()50 return config['available_users']['users']51def get_oncall_config_last_modified_time():52 config = _get_oncall_config()53 return config['current_config']['last_modified_time']54def get_oncall_config_last_modified_user_id():55 config = _get_oncall_config()56 return config['current_config']['last_modified_user_id']57def lookup_user_by_phone(phonenum):58 config = _get_oncall_config()59 for user_id, user_dict in config['available_users']['users'].items():60 if phonenum == user_dict['phone']:61 return user_dict62 return None63def _validate_oncall_config(config_dict):64 assert 'current_config' in config_dict, 'Top-level current_config not present'65 assert 'oncall_user' in config_dict['current_config'], 'current_config.oncall_user not present'66 assert _validate_user(config_dict['current_config']['oncall_user']), 'current_config.oncall_user fails validation'67 assert _validate_top_contact_items(config_dict['current_config']), 'current_config contact items fail validation'68 assert 'last_modified_time' in config_dict['current_config'], 'current_config.last_modified_time not present'69 assert 'last_modified_user_id' in config_dict['current_config'], 'current_config.last_modified_user_id not present'70 assert 'available_users' in config_dict, 'Top-level available_users not present'71 assert 'users' in config_dict['available_users'], 'available_users.users not present'72 for user_id, user_dict in config_dict['available_users']['users'].items():73 assert _validate_user(user_dict), 'available_users item ' + user_id + ' failed validation'74 assert _validate_available_users_unique(config_dict['available_users']), 'available_users failed uniqueness check'75 assert _validate_mail_settings(config_dict['current_config']['mail_settings']), 'current_config.mail_settings failed validation'76 assert 'session_lifetime' in config_dict['current_config'], 'current_config.session_lifetime not present'77 return True78def _validate_top_contact_items(current_config):79 assert 'pager_phone' in current_config, 'current_config lacks pager_phone'80 assert re.fullmatch(r"^\+1[2-9][0-9]{2}[2-9][0-9]{6}$", current_config['pager_phone']), 'current_config pager_phone ' + current_config['pager_phone'] + ' failed validation'81 assert 'from_phone' in current_config, 'current_config lacks from_phone'82 assert re.fullmatch(r"^\+1[2-9][0-9]{2}[2-9][0-9]{6}$", current_config['from_phone']), 'current_config from_phone ' + current_config['from_phone'] + ' failed validation'83 return True84def _validate_available_users_unique(available_users_dict):85 phone_dedup = dict()86 name_dedup = dict()87 for user_id, user_dict in available_users_dict['users'].items():88 assert user_dict['id'] == user_id, 'Available user record outer ID ' + user_id + ' mismatched with inner id ' + user_dict['id']89 assert user_dict['phone'] not in phone_dedup, 'Phone ' + user_dict['phone'] + ' is not unique among available users'90 phone_dedup[user_dict['phone']] = user_dict['phone']91 assert user_dict['name'] not in name_dedup, 'Name ' + user_dict['name'] + ' is not unique among available users'.format(user_dict['phone'])92 name_dedup[user_dict['name']] = user_dict['name']93 return True94def _validate_user(user_dict):95 assert 'id' in user_dict, 'User id not present'96 assert 'name' in user_dict, 'User name not present'97 assert 'phone' in user_dict, 'User phone not present'98 assert re.fullmatch(r"^\+1[2-9][0-9]{2}[2-9][0-9]{6}$", user_dict['phone']), 'User phone ' + user_dict['phone'] + ' failed validation'99 return True100def _validate_mail_settings(mail_settings):101 assert 'from_email' in mail_settings, 'current_config.mail_settings lacks from_email'102 assert re.fullmatch(r"\S+@\S+\.\S+", mail_settings['from_email']), 'current_config.mail_settings from_email ' + mail_settings['from_email'] + ' failed validation'103 assert 'mail_password' in mail_settings, 'current_config.mail_settings lacks mail_password'104 assert 'mail_port' in mail_settings, 'current_config.mail_settings lacks mail_port'105 assert 'mail_server' in mail_settings, 'current_config.mail_settings lacks mail_server'106 assert 'mail_use_tls' in mail_settings, 'current_config.mail_settings lacks mail_use_tls'107 assert 'mail_username' in mail_settings, 'current_config.mail_settings lacks mail_user'108 assert 'to_email' in mail_settings, 'current_config.mail_settings lacks to_email'109 assert re.fullmatch(r"\S+@\S+\.\S+", mail_settings['to_email']), 'current_config.mail_settings to_email ' + mail_settings['to_email'] + ' failed validation'110 return True111def _get_oncall_config():112 s3c = boto3.client('s3')113 config_obj = s3c.get_object(Bucket=os.getenv('BACKING_STORE_S3_BUCKET'), Key=os.getenv('BACKING_STORE_S3_KEY'))114 config_dict = json.loads(config_obj['Body'].read())115 if _validate_oncall_config(config_dict):116 return config_dict117 else:118 return {}119def _set_oncall_config(config_dict, actor_id):120 config_dict['current_config']['last_modified_time'] = int(time.time())121 config_dict['current_config']['last_modified_user_id'] = actor_id122 assert _validate_oncall_config(config_dict)123 s3c = boto3.client('s3')124 s3c.put_object(Bucket=os.getenv('BACKING_STORE_S3_BUCKET'), Key=os.getenv('BACKING_STORE_S3_KEY'), Body=json.dumps(config_dict, sort_keys=True, indent=4))...
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!!