| Total Complexity | 57 | 
| Total Lines | 270 | 
| Duplicated Lines | 92.22 % | 
| Changes | 0 | ||
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like equipment_carbon_input_category often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import time  | 
            ||
| 2 | from datetime import datetime, timedelta  | 
            ||
| 3 | from decimal import Decimal  | 
            ||
| 4 | import mysql.connector  | 
            ||
| 5 | import carbon_dioxide_emmision_factor  | 
            ||
| 6 | import config  | 
            ||
| 7 | |||
| 8 | |||
| 9 | ########################################################################################################################  | 
            ||
| 10 | # PROCEDURES  | 
            ||
| 11 | # Step 1: get all equipments  | 
            ||
| 12 | # for each equipment in list:  | 
            ||
| 13 | # Step 2: get the latest start_datetime_utc  | 
            ||
| 14 | # Step 3: get all energy input data since the latest start_datetime_utc  | 
            ||
| 15 | # Step 4: get carbon dioxide emission factor  | 
            ||
| 16 | # Step 5: calculate carbon dioxide emission by multiplying energy with factor  | 
            ||
| 17 | # Step 6: save carbon dioxide emission data to database  | 
            ||
| 18 | ########################################################################################################################  | 
            ||
| 19 | |||
| 20 | |||
| 21 | View Code Duplication | def main(logger):  | 
            |
| 
                                                                                                    
                        
                         | 
                |||
| 22 | |||
| 23 | while True:  | 
            ||
| 24 | # the outermost while loop  | 
            ||
| 25 | ################################################################################################################  | 
            ||
| 26 | # Step 1: get all equipments  | 
            ||
| 27 | ################################################################################################################  | 
            ||
| 28 | cnx_system_db = None  | 
            ||
| 29 | cursor_system_db = None  | 
            ||
| 30 | try:  | 
            ||
| 31 | cnx_system_db = mysql.connector.connect(**config.myems_system_db)  | 
            ||
| 32 | cursor_system_db = cnx_system_db.cursor()  | 
            ||
| 33 | except Exception as e:  | 
            ||
| 34 |             logger.error("Error in step 1.1 of equipment_carbon_input_category " + str(e)) | 
            ||
| 35 | if cursor_system_db:  | 
            ||
| 36 | cursor_system_db.close()  | 
            ||
| 37 | if cnx_system_db:  | 
            ||
| 38 | cnx_system_db.close()  | 
            ||
| 39 | # sleep and continue the outermost while loop  | 
            ||
| 40 | time.sleep(60)  | 
            ||
| 41 | continue  | 
            ||
| 42 | |||
| 43 |         print("Connected to MyEMS System Database") | 
            ||
| 44 | |||
| 45 | equipment_list = list()  | 
            ||
| 46 | try:  | 
            ||
| 47 |             cursor_system_db.execute(" SELECT id, name, cost_center_id " | 
            ||
| 48 | " FROM tbl_equipments "  | 
            ||
| 49 | " ORDER BY id ")  | 
            ||
| 50 | rows_equipments = cursor_system_db.fetchall()  | 
            ||
| 51 | |||
| 52 | if rows_equipments is None or len(rows_equipments) == 0:  | 
            ||
| 53 |                 print("Step 1.2: There isn't any equipments. ") | 
            ||
| 54 | if cursor_system_db:  | 
            ||
| 55 | cursor_system_db.close()  | 
            ||
| 56 | if cnx_system_db:  | 
            ||
| 57 | cnx_system_db.close()  | 
            ||
| 58 | # sleep and continue the outermost while loop  | 
            ||
| 59 | time.sleep(60)  | 
            ||
| 60 | continue  | 
            ||
| 61 | |||
| 62 | for row in rows_equipments:  | 
            ||
| 63 |                 equipment_list.append({"id": row[0], "name": row[1], "cost_center_id": row[2]}) | 
            ||
| 64 | |||
| 65 | except Exception as e:  | 
            ||
| 66 |             logger.error("Error in step 1.2 of equipment_carbon_input_category " + str(e)) | 
            ||
| 67 | if cursor_system_db:  | 
            ||
| 68 | cursor_system_db.close()  | 
            ||
| 69 | if cnx_system_db:  | 
            ||
| 70 | cnx_system_db.close()  | 
            ||
| 71 | # sleep and continue the outermost while loop  | 
            ||
| 72 | time.sleep(60)  | 
            ||
| 73 | continue  | 
            ||
| 74 | |||
| 75 |         print("Step 1.2: Got all equipments from MyEMS System Database") | 
            ||
| 76 | |||
| 77 | cnx_energy_db = None  | 
            ||
| 78 | cursor_energy_db = None  | 
            ||
| 79 | try:  | 
            ||
| 80 | cnx_energy_db = mysql.connector.connect(**config.myems_energy_db)  | 
            ||
| 81 | cursor_energy_db = cnx_energy_db.cursor()  | 
            ||
| 82 | except Exception as e:  | 
            ||
| 83 |             logger.error("Error in step 1.3 of equipment_carbon_input_category " + str(e)) | 
            ||
| 84 | if cursor_energy_db:  | 
            ||
| 85 | cursor_energy_db.close()  | 
            ||
| 86 | if cnx_energy_db:  | 
            ||
| 87 | cnx_energy_db.close()  | 
            ||
| 88 | |||
| 89 | if cursor_system_db:  | 
            ||
| 90 | cursor_system_db.close()  | 
            ||
| 91 | if cnx_system_db:  | 
            ||
| 92 | cnx_system_db.close()  | 
            ||
| 93 | # sleep and continue the outermost while loop  | 
            ||
| 94 | time.sleep(60)  | 
            ||
| 95 | continue  | 
            ||
| 96 | |||
| 97 |         print("Connected to MyEMS Energy Database") | 
            ||
| 98 | |||
| 99 | cnx_carbon_db = None  | 
            ||
| 100 | cursor_carbon_db = None  | 
            ||
| 101 | try:  | 
            ||
| 102 | cnx_carbon_db = mysql.connector.connect(**config.myems_carbon_db)  | 
            ||
| 103 | cursor_carbon_db = cnx_carbon_db.cursor()  | 
            ||
| 104 | except Exception as e:  | 
            ||
| 105 |             logger.error("Error in step 1.4 of equipment_carbon_input_category " + str(e)) | 
            ||
| 106 | if cursor_carbon_db:  | 
            ||
| 107 | cursor_carbon_db.close()  | 
            ||
| 108 | if cnx_carbon_db:  | 
            ||
| 109 | cnx_carbon_db.close()  | 
            ||
| 110 | |||
| 111 | if cursor_energy_db:  | 
            ||
| 112 | cursor_energy_db.close()  | 
            ||
| 113 | if cnx_energy_db:  | 
            ||
| 114 | cnx_energy_db.close()  | 
            ||
| 115 | |||
| 116 | if cursor_system_db:  | 
            ||
| 117 | cursor_system_db.close()  | 
            ||
| 118 | if cnx_system_db:  | 
            ||
| 119 | cnx_system_db.close()  | 
            ||
| 120 | # sleep and continue the outermost while loop  | 
            ||
| 121 | time.sleep(60)  | 
            ||
| 122 | continue  | 
            ||
| 123 | |||
| 124 |         print("Connected to MyEMS Carbon Database") | 
            ||
| 125 | |||
| 126 | for equipment in equipment_list:  | 
            ||
| 127 | |||
| 128 | ############################################################################################################  | 
            ||
| 129 | # Step 2: get the latest start_datetime_utc  | 
            ||
| 130 | ############################################################################################################  | 
            ||
| 131 |             print("Step 2: get the latest start_datetime_utc from carbon database for " + equipment['name']) | 
            ||
| 132 | try:  | 
            ||
| 133 |                 cursor_carbon_db.execute(" SELECT MAX(start_datetime_utc) " | 
            ||
| 134 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 135 | " WHERE equipment_id = %s ",  | 
            ||
| 136 | (equipment['id'], ))  | 
            ||
| 137 | row_datetime = cursor_carbon_db.fetchone()  | 
            ||
| 138 | start_datetime_utc = datetime.strptime(config.start_datetime_utc, '%Y-%m-%d %H:%M:%S')  | 
            ||
| 139 | start_datetime_utc = start_datetime_utc.replace(minute=0, second=0, microsecond=0, tzinfo=None)  | 
            ||
| 140 | |||
| 141 | if row_datetime is not None and len(row_datetime) > 0 and isinstance(row_datetime[0], datetime):  | 
            ||
| 142 | # replace second and microsecond with 0  | 
            ||
| 143 | # note: do not replace minute in case of calculating in half hourly  | 
            ||
| 144 | start_datetime_utc = row_datetime[0].replace(second=0, microsecond=0, tzinfo=None)  | 
            ||
| 145 | # start from the next time slot  | 
            ||
| 146 | start_datetime_utc += timedelta(minutes=config.minutes_to_count)  | 
            ||
| 147 | |||
| 148 |                 print("start_datetime_utc: " + start_datetime_utc.isoformat()[0:19]) | 
            ||
| 149 | except Exception as e:  | 
            ||
| 150 |                 logger.error("Error in step 2 of equipment_carbon_input_category " + str(e)) | 
            ||
| 151 | # break the for equipment loop  | 
            ||
| 152 | break  | 
            ||
| 153 | |||
| 154 | ############################################################################################################  | 
            ||
| 155 | # Step 3: get all energy input data since the latest start_datetime_utc  | 
            ||
| 156 | ############################################################################################################  | 
            ||
| 157 |             print("Step 3: get all energy input data since the latest start_datetime_utc") | 
            ||
| 158 | |||
| 159 |             query = (" SELECT start_datetime_utc, energy_category_id, actual_value " | 
            ||
| 160 | " FROM tbl_equipment_input_category_hourly "  | 
            ||
| 161 | " WHERE equipment_id = %s AND start_datetime_utc >= %s "  | 
            ||
| 162 | " ORDER BY id ")  | 
            ||
| 163 | cursor_energy_db.execute(query, (equipment['id'], start_datetime_utc, ))  | 
            ||
| 164 | rows_hourly = cursor_energy_db.fetchall()  | 
            ||
| 165 | |||
| 166 | if rows_hourly is None or len(rows_hourly) == 0:  | 
            ||
| 167 |                 print("Step 3: There isn't any energy input data to calculate. ") | 
            ||
| 168 | # continue the for equipment loop  | 
            ||
| 169 | continue  | 
            ||
| 170 | |||
| 171 | energy_dict = dict()  | 
            ||
| 172 | energy_category_list = list()  | 
            ||
| 173 | end_datetime_utc = start_datetime_utc  | 
            ||
| 174 | for row_hourly in rows_hourly:  | 
            ||
| 175 | current_datetime_utc = row_hourly[0]  | 
            ||
| 176 | energy_category_id = row_hourly[1]  | 
            ||
| 177 | |||
| 178 | if energy_category_id not in energy_category_list:  | 
            ||
| 179 | energy_category_list.append(energy_category_id)  | 
            ||
| 180 | |||
| 181 | actual_value = row_hourly[2]  | 
            ||
| 182 | if energy_dict.get(current_datetime_utc) is None:  | 
            ||
| 183 | energy_dict[current_datetime_utc] = dict()  | 
            ||
| 184 | energy_dict[current_datetime_utc][energy_category_id] = actual_value  | 
            ||
| 185 | if current_datetime_utc > end_datetime_utc:  | 
            ||
| 186 | end_datetime_utc = current_datetime_utc  | 
            ||
| 187 | |||
| 188 | ############################################################################################################  | 
            ||
| 189 | # Step 4: get carbon dioxide emission factor  | 
            ||
| 190 | ############################################################################################################  | 
            ||
| 191 |             print("Step 4: get carbon dioxide emission factor") | 
            ||
| 192 | factor_dict = dict()  | 
            ||
| 193 | for energy_category_id in energy_category_list:  | 
            ||
| 194 | factor_dict[energy_category_id] = \  | 
            ||
| 195 | carbon_dioxide_emmision_factor.get_energy_category_factor(  | 
            ||
| 196 | energy_category_id,  | 
            ||
| 197 | start_datetime_utc,  | 
            ||
| 198 | end_datetime_utc)  | 
            ||
| 199 | ############################################################################################################  | 
            ||
| 200 | # Step 5: calculate carbon dioxide emission by multiplying energy with factor  | 
            ||
| 201 | ############################################################################################################  | 
            ||
| 202 |             print("Step 5: calculate carbon dioxide emission by multiplying energy with factor") | 
            ||
| 203 | carbon_dict = dict()  | 
            ||
| 204 | |||
| 205 | if len(energy_dict) > 0:  | 
            ||
| 206 | for current_datetime_utc in energy_dict.keys():  | 
            ||
| 207 | carbon_dict[current_datetime_utc] = dict()  | 
            ||
| 208 | for energy_category_id in energy_category_list:  | 
            ||
| 209 | current_factor = factor_dict[energy_category_id]  | 
            ||
| 210 | current_energy = energy_dict[current_datetime_utc].get(energy_category_id)  | 
            ||
| 211 | if current_factor is not None \  | 
            ||
| 212 | and isinstance(current_factor, Decimal) \  | 
            ||
| 213 | and current_energy is not None \  | 
            ||
| 214 | and isinstance(current_energy, Decimal):  | 
            ||
| 215 | carbon_dict[current_datetime_utc][energy_category_id] = \  | 
            ||
| 216 | current_energy * current_factor  | 
            ||
| 217 | |||
| 218 | if len(carbon_dict[current_datetime_utc]) == 0:  | 
            ||
| 219 | del carbon_dict[current_datetime_utc]  | 
            ||
| 220 | |||
| 221 | ############################################################################################################  | 
            ||
| 222 | # Step 6: save carbon dioxide emission data to database  | 
            ||
| 223 | ############################################################################################################  | 
            ||
| 224 |             print("Step 6: save carbon dioxide emission data to database") | 
            ||
| 225 | |||
| 226 | if len(carbon_dict) > 0:  | 
            ||
| 227 | try:  | 
            ||
| 228 |                     add_values = (" INSERT INTO tbl_equipment_input_category_hourly " | 
            ||
| 229 | " (equipment_id, "  | 
            ||
| 230 | " energy_category_id, "  | 
            ||
| 231 | " start_datetime_utc, "  | 
            ||
| 232 | " actual_value) "  | 
            ||
| 233 | " VALUES ")  | 
            ||
| 234 | |||
| 235 | for current_datetime_utc in carbon_dict:  | 
            ||
| 236 | for energy_category_id in energy_category_list:  | 
            ||
| 237 | current_carbon = carbon_dict[current_datetime_utc].get(energy_category_id)  | 
            ||
| 238 | if current_carbon is not None and isinstance(current_carbon, Decimal):  | 
            ||
| 239 |                                 add_values += " (" + str(equipment['id']) + "," | 
            ||
| 240 | add_values += " " + str(energy_category_id) + ","  | 
            ||
| 241 | add_values += "'" + current_datetime_utc.isoformat()[0:19] + "',"  | 
            ||
| 242 | add_values += str(current_carbon[current_datetime_utc][energy_category_id]) + "), "  | 
            ||
| 243 |                     print("add_values:" + add_values) | 
            ||
| 244 | # trim ", " at the end of string and then execute  | 
            ||
| 245 | cursor_carbon_db.execute(add_values[:-2])  | 
            ||
| 246 | cnx_carbon_db.commit()  | 
            ||
| 247 | except Exception as e:  | 
            ||
| 248 |                     logger.error("Error in step 6 of equipment_carbon_input_category " + str(e)) | 
            ||
| 249 | # break the for equipment loop  | 
            ||
| 250 | break  | 
            ||
| 251 | |||
| 252 | # end of for equipment loop  | 
            ||
| 253 | if cursor_system_db:  | 
            ||
| 254 | cursor_system_db.close()  | 
            ||
| 255 | if cnx_system_db:  | 
            ||
| 256 | cnx_system_db.close()  | 
            ||
| 257 | |||
| 258 | if cursor_energy_db:  | 
            ||
| 259 | cursor_energy_db.close()  | 
            ||
| 260 | if cnx_energy_db:  | 
            ||
| 261 | cnx_energy_db.close()  | 
            ||
| 262 | |||
| 263 | if cursor_carbon_db:  | 
            ||
| 264 | cursor_carbon_db.close()  | 
            ||
| 265 | if cnx_carbon_db:  | 
            ||
| 266 | cnx_carbon_db.close()  | 
            ||
| 267 |         print("go to sleep 300 seconds...") | 
            ||
| 268 | time.sleep(300)  | 
            ||
| 269 |         print("wake from sleep, and continue to work...") | 
            ||
| 270 | # end of the outermost while loop  | 
            ||
| 271 |