Best Python code snippet using robotframework-appiumlibrary_python
Handson.py
Source:Handson.py
1import sys2import pandas as pd3from tensorboard import summary4#================================================================5# main()6#================================================================7def main():8 #-------------------------------------------------9 # ã¢ã³ã±ã¼ãåççµæã®Excelãä½æ¥ãã©ã«ãã«ã³ãã¼10 #-------------------------------------------------11 file_path_src = r"C:\Users\e13971\Konica Minolta\Pythonããã°ã©ãã³ã°GP - ããã¥ã¡ã³ã\General\Day1\ã¢ã³ã±ã¼ã\Pythonããã°ã©ãã³ã°å
¥é_Day1ã¢ã³ã±ã¼ã.xlsx"12 file_path_dsc = r"C:\Users\e13971\Desktop\FY22PythonStudy\FY22Pythonstudy\Pythonããã°ã©ãã³ã°å
¥é_Day1ã¢ã³ã±ã¼ã.xlsx"13 import shutil14 shutil.copy(file_path_src,file_path_dsc)15 #-------------------------------------------------16 # ãã¡ã¤ã«ããDataFrameã«ãã¼ã¿ãèªã¿è¾¼ã17 #-------------------------------------------------18 global df_excel_data19 df_excel_data = pd.read_excel(file_path_dsc)20 print("[åçæ°]{0}".format(len(df_excel_data)))21 print("")22 #------------------------------------------------23 # ã¢ã³ã±ã¼ãã®åççµæãéè¨ã»è¡¨ç¤º24 #------------------------------------------------25 #============== Q1 ==============26 q1_question = "ãåä¸é¸æãä¸è¨ã®é¸æè¢ã®ä¸ã§ã¹ãããè²·ãã¨ãã«æãéè¦ããé
ç®ã©ãã§ããï¼[A]"27 q1_row = ["ä¾¡æ ¼", "ãµã¤ãº", "éã", "ãã¶ã¤ã³", "ã«ã¡ã©ã®ç»è³ª", "ç»é¢ã®è§£å度"]28 q1_column = ["é¸æãããæ°"]29 df_q1_result = pd.DataFrame(index=q1_row,columns=q1_column)30 for col_name, col in df_q1_result.iteritems():31 for row_name in col.index:32 df_q1_result.loc[row_name,col_name] = 033 for row_name, row in df_excel_data.iterrows():34 sel = row[q1_question]35 df_q1_result.loc[sel,q1_column[0]] += 136 print("[Q1] "+ q1_question)37 for sel,row in df_q1_result.iterrows():38 print("ã»{0}:{1}".format(sel,df_q1_result.loc[sel, q1_column[0]]))39 print("")40 #============== Q2 ==============41 q2_question = "ããªãã«ã¼ããä¸è¨ã®å£ç¯ã®å¥½ãå«ããçãã¦ä¸ããã[B]"42 q2_row = ["çå¬[B01]", "æ¥[B02]", "åå¤[B03]", "æ¢
é¨[B04]", "çå¤[B05]", "åç§[B06]", "æ©ç§[B07]"]43 q2_column = ["大好ã", "ããã¨å¥½ã", "ã©ã¡ãã§ããªã", "ãã¾ã好ãã§ã¯ãªã", "å«ã"]44 df_q2_result = pd.DataFrame(index=q2_row,columns=q2_column)45 for col_name, col in df_q2_result.iteritems():46 for row_name in col.index:47 df_q2_result.loc[row_name,col_name] = 048 for row_name, row in df_excel_data.iterrows():49 for question in q2_row:50 answer = row[question]51 df_q2_result.at[question,answer] += 152 print("[Q2] "+ q2_question)53 print(df_q2_result)54 print("")55 # #============== Q3 ==============56 q3_question = "ãè¤æ°é¸æãä¸è¨ã®é¸æè¢ã®ä¸ã§ãã¬ããè²·ãã¨ãã«éè¦ããé
ç®ãé¸ãã§ä¸ããï¼è¤æ°é¸æå¯ï¼[C]"57 q3_row = ["ä¾¡æ ¼", "é³è³ª", "ç»è³ª", "ç»é¢ãµã¤ãº", "ãã¶ã¤ã³", "ãªã¢ã³ã³ã®ä½¿ãããã", "ã¢ãã¿ã¼ãµã¼ãã¹"]58 q3_column = ["é¸æãããæ°"]59 df_q3_result = pd.DataFrame(index=q3_row,columns=q3_column)60 for col_name, col in df_q3_result.iteritems():61 for row_name in col.index:62 df_q3_result.loc[row_name,col_name] = 063 for row_name, row in df_excel_data.iterrows():64 for sel in df_q3_result.index:65 if sel in row[q3_question]:66 df_q3_result.loc[sel,q3_column[0]] += 167 print("[Q3] "+ q3_question)68 for sel,row in df_q3_result.iterrows():69 print("ã»{0}:{1}".format(sel,df_q3_result.loc[sel, q3_column[0]]))70 print("")71 #------------------------------------------------72 # æ°å¤ã«å¤æããDataFrameãExcelãã¡ã¤ã«ã«åºå73 #------------------------------------------------74 summary_file_path = r"C:\Users\e13971\Desktop\FY22PythonStudy\FY22Pythonstudy\ã¢ã³ã±ã¼ãéè¨.xlsx"75 export_excel(_path = summary_file_path, _df = df_q1_result, _sheet_name = "Q1", _header_fillcol = "66ffcc")76 export_excel(_path = summary_file_path, _df = df_q2_result, _sheet_name = "Q2", _append = True, _header_fillcol = "66ffcc")77 export_excel(_path = summary_file_path, _df = df_q3_result, _sheet_name = "Q3", _append = True, _header_fillcol = "66ffcc")78 #------------------------------------------------79 # åçè
ã«ã¡ã¼ã«ãéä¿¡80 #------------------------------------------------81 import win32com.client82 outlook = win32com.client.Dispatch("outlook.Application")83 mail = outlook.CreateItem(0)84 mail.to = "benshuai.guo@konicaminolta.com"85 mail.subject = "ã¢ã³ã±ã¼ãéè¨çµæ"86 mail.bodyFormat = 2 #HTML87 mail.body = "ã¢ã³ã±ã¼ãçµæãéããã¾ãããããããé¡ããã¾ãã"88 mail.Attachments.Add(summary_file_path)89 if True:90 mail.display(True)91 else:92 mail.Send()93#================================================================94# [export_excel] DataFrameãExcelã¸åºå 95# ç»åãæ¿å
¥ããã¨ãã¯_wbã¯Noneã§ãªããã°ãªããªãï¼_pathã§æå®ããï¼96#================================================================97def export_excel(_path=None, _df=None, _wb=None, _sheet_name='sheet1', _letter_fmt=None, _append=False, _frz='B2', _auto_flt=True, _auto_sz=False, _header_height=None, _col_width_=[20,20], _header_fmt=None, _header_rot=0, _zoom=100, _heatmap=0, _is_index=True, _index_name='Index', _header_txtcol='000000', _header_fillcol='d9f2f8', _txtwrap=False, _img=None, _group=None):98 import os99 import time100 import openpyxl as px101 from openpyxl.utils import get_column_letter102 from openpyxl.comments import Comment103 time_start = time.perf_counter()104 print('[Exporting Excel file ...] Sheet : "{0}"'.format(_sheet_name))105 106 #-------------------------------------------107 # åæè¨å®108 #-------------------------------------------109 # Workbookä½æ110 if _wb == None:111 if _append: # æ¢åãã¡ã¤ã«ã«ã·ã¼ã追å 112 try:113 wb = px.load_workbook(_path)114 except:115 _append = False # ãã¡ã¤ã«ãåå¨ããªãã¨ãã¯æ°è¦ä½æ116 if not _append: # æ°è¦ãã¡ã¤ã«117 wb = px.Workbook()118 else:119 wb = _wb120 _append = True121 # Worksheetä½æ122 ws = wb.create_sheet(title=_sheet_name)123 #-------------------------------------------124 # DataFrameãWorksheetã«æ¸ãè¾¼ã¿125 #-------------------------------------------126 if _df is not None:127 #----- ä½æ¥ç¨ã«DataFrameãã³ãã¼ -----128 df = _df.copy()129 130 # Timestampãæååã«å¤æï¼ãã®ã¾ã¾ã ã¨ã¨ã©ã¼ã«ãªãã®ã§ï¼131 list_timestamp_col = list()132 # Timestampã®ã»ã«ãåå¨ããåãæ¢ãã¦æååã«å¤æãã133 for col_name, col in df.iteritems():134 for item in col:135 tp = type(item)136 if tp is pd._libs.tslibs.timestamps.Timestamp:137 list_timestamp_col.append(col_name)138 break139 for col in list_timestamp_col:140 df[col] = df[col].astype(str)141 df[col] = df[col].replace('NaT', '')142 143 #----- Excelãã¡ã¤ã«ç¨ãã©ã¼ãããã®ä½æ -----144 base_font = '游ã´ã·ãã¯'145 from openpyxl.styles.fonts import Font146 from openpyxl.styles import PatternFill147 font_header_row = Font(name=base_font, b=True, sz=10, color=_header_txtcol)148 font_header_col = Font(name=base_font, b=True, sz=10, color=_header_txtcol)149 font_cell = Font(name=base_font, sz=10)150 align_header_row = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True, textRotation=_header_rot)151 align_header_col = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True)152 fill_header_row = PatternFill(patternType='solid', fgColor=_header_fillcol)153 fill_header_col = PatternFill(patternType='solid', fgColor=_header_fillcol)154 155 #----- ãã¼ã¿åºå -----156 # DataFrameãWorksheetã«Export157 l = df.columns.tolist()158 if _is_index:159 l.insert(0, _index_name) # è¡ã®indexãå
é åã«è¿½å 160 ws.append(l)161 count = 0162 for i, row in df.iterrows(): # ä¸è¡ãã¤wsã«è¿½å ãã¦ãã163 l = row.values.tolist()164 if _is_index:165 l.insert(0, row.name) # è¡ã®indexãå
é åã«è¿½å 166 ws.append(l)167 count += 1168 print('\r - ãã¼ã¿ã³ãã¼ {0}/{1}'.format(count, len(df)), end="")169 print('')170 171 #----- Worksheetã®æ¸å¼è¨å® -----172 # ãããã¼è¡(æ¢å®å¤)173 for cell in list(ws.rows)[0]:174 cell.font = font_header_row175 cell.alignment = align_header_row176 cell.fill = fill_header_row177 # ãããã¼è¡(åå¥)178 if _header_fmt != None:179 list_cell = list(ws.rows)[0]180 for head, fmt in _header_fmt.items():181 try:182 index = list(df.columns).index(head)183 if _is_index:184 index += 1185 cell = list_cell[index]186 except:187 continue188 # rotation189 try:190 rotation = fmt['rotation']191 cell.alignment = px.styles.Alignment(horizontal="center", vertical="center", wrapText=True, textRotation=rotation)192 except:193 pass194 # æåè²195 try:196 text_color = fmt['txtcol']197 cell.font = Font(name=base_font, b=True, sz=10, color=text_color)198 except:199 pass200 # èæ¯è²201 try:202 fill_color = fmt['fillcol']203 cell.fill = PatternFill(patternType='solid', fgColor=fill_color)204 except:205 pass206 # ã³ã¡ã³ã207 try:208 comment = fmt['comment']209 cell.comment = Comment(comment, '')210 except:211 pass212 # åãã¨ã®æ¸å¼è¨å®ç¨ã®ãªã¹ãä½æ213 list_dtxt_pat = list()214 list_dfill_pat = list()215 if _header_fmt != None:216 for head, fmt in _header_fmt.items():217 try:218 index = list(df.columns).index(head)219 if _is_index:220 index += 1221 except:222 continue223 # æåè²224 try:225 text_color = fmt['dtxtcol']226 list_dtxt_pat.append([index, Font(name=base_font, sz=10, color=text_color)])227 except:228 pass229 # èæ¯è²230 try:231 dfill_color = fmt['dfillcol']232 list_dfill_pat.append([index, PatternFill(patternType='solid', fgColor=dfill_color)])233 except:234 pass235 # ãã¼ã¿è¡æ¸å¼è¨å®236 count = 0237 for row in ws.iter_rows(min_row=2): 238 # æ¸å¼è¨å®239 for cell in row:240 cell.font = font_cell241 cell.alignment = px.styles.Alignment(wrapText=_txtwrap)242 # åãã¨ã®æ¸å¼è¨å®ã§ä¸æ¸ã243 for list_pat in list_dtxt_pat: # åå¥è¨å®ãããåãé ã«å¦çãã244 idx = list_pat[0]245 row[idx].font = list_pat[1]246 for list_pat in list_dfill_pat: # åå¥è¨å®ãããåãé ã«å¦çãã247 idx = list_pat[0]248 row[idx].fill = list_pat[1]249 # Indexåãããå ´åã¯Indexç¨è¨å®250 if _is_index:251 row[0].font = font_header_col # å
é åã®ã¿å¤ªå252 row[0].alignment = align_header_col # å
é åã®ã¿ã»ã³ã¿ãªã³ã°253 row[0].fill = fill_header_col # å
é åã®å¡ãã¤ã¶ã254 count += 1255 print('\r - æ¸å¼è¨å® {0}/{1}'.format(count, len(df)), end="")256 print('')257 258 #----- ã»ã«ã®æåæ¸å¼ -----259 if type(_letter_fmt) is dict: # _header_fmtãããã°ä¸è¦ã ãäºææ§ã®ããã«æ®ãã¦ãã260 for col in ws.iter_cols():261 col_name = col[0].value262 if col_name in _letter_fmt:263 num_format = _letter_fmt[col_name]264 for cell in col:265 cell.number_format = num_format266 elif type(_letter_fmt) is str:267 for col in ws.iter_cols():268 for cell in col:269 cell.number_format = _letter_fmt270 # åãã¨ã®åå¥è¨å®ã§ä¸æ¸ã 271 if _header_fmt != None:272 list_col = list(_header_fmt.keys())273 for col in ws.iter_cols():274 col_name = col[0].value275 if col_name in list_col: # åæ¸å¼ä¸è¦§ã®è¾æ¸ã«ãã®åãåå¨ãã276 try:277 fmt = _header_fmt[col_name]278 num_format = fmt['dtxtformat']279 for cell in col:280 cell.number_format = num_format281 except:282 pass283 284 # Worksheetã®åå¹
調æ´285 if _auto_sz: # èªå調æ´286 for col in ws.columns:287 max_length = 0288 column = col[0].column289 column = get_column_letter(column) # æ°åãã¢ã«ãã¡ãããã«å¤æ290 cols = col if _header_rot!=90 else col[1:]291 for cell in cols:292 if len(str(cell.value)) > max_length:293 max_length = len(str(cell.value))294 adjusted_width = (max_length + 2) * 1.1295 ws.column_dimensions[column].width = adjusted_width296 else:297 for col in ws.columns:298 column = col[0].column # åçªå·ãåå¾299 col_letter = get_column_letter(column) # åçªå·ãåè¨å·ã«å¤æ300 width = _col_width_[0] if column == 1 else _col_width_[1] # åå¹
301 ws.column_dimensions[col_letter].width = width302 # åãã¨ã®åå¥èª¿æ´303 if _header_fmt != None:304 list_col = list(ws.columns)305 for head, fmt in _header_fmt.items():306 try:307 width = fmt['width']308 index = list(df.columns).index(head)309 if _is_index:310 index += 1311 col = list_col[index]312 column = col[0].column # åçªå·ãåå¾313 col_letter = get_column_letter(column) # åçªå·ãåè¨å·ã«å¤æ314 ws.column_dimensions[col_letter].width = width315 except:316 pass317 318 # Worksheetã®è¡ã®é«ã調æ´319 if _header_height != None:320 ws.row_dimensions[1].height = _header_height321 322 # ãã¼ãããã323 from openpyxl.formatting.rule import ColorScale, FormatObject324 from openpyxl.styles import Color325 if _heatmap == 1: # 赤 â ç½ â é326 first = FormatObject(type='min')327 last = FormatObject(type='max')328 # colors match the format objects:329 colors = [Color('F8696B'), Color('5A8AC6')]330 # a three color scale would extend the sequences331 mid = FormatObject(type='percentile', val=50)332 colors.insert(1, Color('FCFCFF'))333 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)334 # create a rule with the color scale335 from openpyxl.formatting.rule import Rule336 rule = Rule(type='colorScale', colorScale=cs3)337 # 対象ç¯å²ã示ãæååãä½æ338 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)339 ws.conditional_formatting.add(rg, rule)340 elif _heatmap == 2: # ç½ â æ© â 赤341 first = FormatObject(type='min')342 last = FormatObject(type='max')343 # colors match the format objects:344 colors = [Color('FFFFFF'), Color('F8696B')]345 # a three color scale would extend the sequences346 mid = FormatObject(type='percentile', val=50)347 colors.insert(1, Color('FFEB84'))348 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)349 # create a rule with the color scale350 from openpyxl.formatting.rule import Rule351 rule = Rule(type='colorScale', colorScale=cs3)352 # 対象ç¯å²ã示ãæååãä½æ353 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)354 ws.conditional_formatting.add(rg, rule)355 elif _heatmap == 3: # 赤 â æ© â ç½356 first = FormatObject(type='min')357 last = FormatObject(type='max')358 # colors match the format objects:359 colors = [Color('F8696B'), Color('FFFFFF')]360 # a three color scale would extend the sequences361 mid = FormatObject(type='percentile', val=25)362 colors.insert(1, Color('FFEB84'))363 cs3 = ColorScale(cfvo=[first, mid, last], color=colors)364 # create a rule with the color scale365 from openpyxl.formatting.rule import Rule366 rule = Rule(type='colorScale', colorScale=cs3)367 # 対象ç¯å²ã示ãæååãä½æ368 rg = 'A2:' + get_column_letter(ws.max_column)+str(ws.max_row)369 ws.conditional_formatting.add(rg, rule)370 371 # æ åºå®372 if _frz != None:373 ws.freeze_panes = _frz374 # ãªã¼ããã£ã«ã¿375 if _auto_flt:376 ws.auto_filter.ref = 'A1:' + get_column_letter(ws.max_column)+'1'377 378 # ã°ã«ã¼ãå([0]éå§åå [1]çµäºåå [2]éããæTrue)379 if _group != None:380 for r in _group:381 if r[0] < r[1]:382 ws.column_dimensions.group(get_column_letter(r[0]), get_column_letter(r[1]), hidden=r[2])383 384 # 表示åç385 ws.sheet_view.zoomScale = _zoom386 387 #-------------------------------------------388 # Worksheetã«ç»åãæ¿å
¥389 #-------------------------------------------390 if _img != None:391 from openpyxl.drawing.image import Image392 for img in _img:393 fpath = img[0] # æ¿å
¥ããç»åãã¡ã¤ã«394 anchor = img[1] # æ¿å
¥ä½ç½®395 px_img = Image(fpath)396 px_img.anchor = anchor397 ws.add_image(px_img)398 399 #-------------------------------------------400 # æå¾ã«ä¸è¦ãªã·ã¼ããåé¤401 #-------------------------------------------402 if 'Sheet' in wb.sheetnames:403 wb.remove(wb['Sheet'])404 #-------------------------------------------405 # Excelãã¡ã¤ã«ã«æ¸ãè¾¼ã¿406 #-------------------------------------------407 if _path != None:408 print(' - ãã¡ã¤ã«æ¸ãè¾¼ã¿...', end='')409 wb.save(_path)410 # ç»åãã¡ã¤ã«åé¤411 if _img != None:412 for img in _img:413 is_delete = False # ãã¡ã¤ã«ãåé¤ãããå¦ã414 if len(img) > 2:415 is_delete = img[2]416 if is_delete: # ãã¡ã¤ã«åé¤417 os.remove(img[0])418 print ('\n ---> Finished. (å¦çæé:{0:.3f}[sec])'.format(time.perf_counter() - time_start ))419 420 return wb421if __name__ == "__main__":422 import time423 main_time_start = time.perf_counter()424 main()425 print("\n===> æ£å¸¸çµäº (å¦çæé:{:.3f}[sec])".format(time.perf_counter()-main_time_start))...
test_pandabar.py
Source:test_pandabar.py
1import unittest2from numpy import float643from pandasio.pandabar import _PandaBar, _get_panda_bar_info_dtype4from pandasio.exceptions import IdentifierByteRepresentationError5from pandasio.utils.exceptions import NumBytesForStringInvalidError6from pandasio.utils.numpy_utils import NumpyTypeChars7class TestPandaBar(unittest.TestCase):8 def test_panda_bar_info_dtype(self):9 d = _get_panda_bar_info_dtype(4)10 self.assertEqual('identifier', d.descr[0][0])11 self.assertEqual('<U1', d.descr[0][1])12 self.assertEqual('options', d.descr[1][0])13 self.assertEqual('<u2', d.descr[1][1])14 self.assertEqual('bytes_per_point', d.descr[2][0])15 self.assertEqual('|u1', d.descr[2][1])16 self.assertEqual('type_char', d.descr[3][0])17 self.assertEqual('|u1', d.descr[3][1])18 self.assertEqual('bytes_extra_information', d.descr[4][0])19 self.assertEqual('<u4', d.descr[4][1])20 for i in range(0, 32):21 self.assertEqual('def_byte_{}'.format(i + 1), d.descr[5 + i][0])22 self.assertEqual('|u1', d.descr[5 + i][1])23 d = _get_panda_bar_info_dtype(16)24 self.assertEqual('<U4', d.descr[0][1])25 d = _get_panda_bar_info_dtype(32)26 self.assertEqual('<U8', d.descr[0][1])27 # test errors28 with self.assertRaises(NumBytesForStringInvalidError):29 _get_panda_bar_info_dtype(2)30 with self.assertRaises(IdentifierByteRepresentationError):31 _get_panda_bar_info_dtype(0)32 with self.assertRaises(IdentifierByteRepresentationError):33 _get_panda_bar_info_dtype(-1)34 with self.assertRaises(NumBytesForStringInvalidError):35 _get_panda_bar_info_dtype(0.5)36 return37 def test_panda_bar_init_min_params(self):38 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)39 self.assertEqual('data', p._identifier)40 self.assertEqual(8, p._bytes_per_value)41 self.assertEqual('f', p._type_char)42 self.assertEqual(float64, p._dtype)43 self.assertEqual(False, p._is_index)44 self.assertEqual(None, p._data)45 self.assertEqual(None, p._encoded_data)46 self.assertEqual(None, p._num_points)47 self.assertEqual(True, p._use_compression)48 self.assertEqual(False, p._use_hash_table)49 self.assertEqual(False, p._use_floating_point_rounding)50 self.assertEqual(None, p._compression_dtype)51 self.assertEqual(None, p._compression_mode)52 self.assertEqual(None, p._compression_reference_value)53 self.assertEqual(None, p._compression_reference_value_dtype)54 self.assertEqual(None, p._floating_point_rounding_num_decimals)55 self.assertEqual(0, p._num_bytes_extra_information)56 return57 def test_panda_bar_init_optional_params(self):58 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT, is_index=True)59 self.assertEqual(True, p._is_index)60 self.assertEqual(True, p.is_index())61 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT, num_extra_bytes_required=4)62 self.assertEqual(4, p._num_bytes_extra_information)63 self.assertEqual(4, p.num_extra_bytes_required())64 return65 def test_panda_bar_encode_options(self):66 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)67 p._use_floating_point_rounding = False68 p._use_hash_table = False69 p._use_compression = False70 p._is_index = False71 self.assertEqual(0, p._encode_options())72 p._use_floating_point_rounding = False73 p._use_hash_table = False74 p._use_compression = False75 p._is_index = True76 self.assertEqual(1, p._encode_options())77 p._use_floating_point_rounding = False78 p._use_hash_table = False79 p._use_compression = True80 p._is_index = False81 self.assertEqual(2, p._encode_options())82 p._use_floating_point_rounding = False83 p._use_hash_table = False84 p._use_compression = True85 p._is_index = True86 self.assertEqual(3, p._encode_options())87 p._use_floating_point_rounding = False88 p._use_hash_table = True89 p._use_compression = False90 p._is_index = False91 self.assertEqual(4, p._encode_options())92 p._use_floating_point_rounding = False93 p._use_hash_table = True94 p._use_compression = False95 p._is_index = True96 self.assertEqual(5, p._encode_options())97 p._use_floating_point_rounding = False98 p._use_hash_table = True99 p._use_compression = True100 p._is_index = False101 self.assertEqual(6, p._encode_options())102 p._use_floating_point_rounding = False103 p._use_hash_table = True104 p._use_compression = True105 p._is_index = True106 self.assertEqual(7, p._encode_options())107 p._use_floating_point_rounding = True108 p._use_hash_table = False109 p._use_compression = False110 p._is_index = False111 self.assertEqual(8, p._encode_options())112 p._use_floating_point_rounding = True113 p._use_hash_table = False114 p._use_compression = False115 p._is_index = True116 self.assertEqual(9, p._encode_options())117 p._use_floating_point_rounding = True118 p._use_hash_table = False119 p._use_compression = True120 p._is_index = False121 self.assertEqual(10, p._encode_options())122 p._use_floating_point_rounding = True123 p._use_hash_table = False124 p._use_compression = True125 p._is_index = True126 self.assertEqual(11, p._encode_options())127 p._use_floating_point_rounding = True128 p._use_hash_table = True129 p._use_compression = False130 p._is_index = False131 self.assertEqual(12, p._encode_options())132 p._use_floating_point_rounding = True133 p._use_hash_table = True134 p._use_compression = False135 p._is_index = True136 self.assertEqual(13, p._encode_options())137 p._use_floating_point_rounding = True138 p._use_hash_table = True139 p._use_compression = True140 p._is_index = False141 self.assertEqual(14, p._encode_options())142 p._use_floating_point_rounding = True143 p._use_hash_table = True144 p._use_compression = True145 p._is_index = True146 self.assertEqual(15, p._encode_options())147 return148 def test_panda_bar_decode_options(self):149 p = _PandaBar('data', 8, NumpyTypeChars.FLOAT)150 p._decode_options(0)151 self.assertFalse(p._use_floating_point_rounding)152 self.assertFalse(p._use_hash_table)153 self.assertFalse(p._use_compression)154 self.assertFalse(p._is_index)155 p._decode_options(1)156 self.assertFalse(p._use_floating_point_rounding)157 self.assertFalse(p._use_hash_table)158 self.assertFalse(p._use_compression)159 self.assertTrue(p._is_index)160 p._decode_options(2)161 self.assertFalse(p._use_floating_point_rounding)162 self.assertFalse(p._use_hash_table)163 self.assertTrue(p._use_compression)164 self.assertFalse(p._is_index)165 p._decode_options(3)166 self.assertFalse(p._use_floating_point_rounding)167 self.assertFalse(p._use_hash_table)168 self.assertTrue(p._use_compression)169 self.assertTrue(p._is_index)170 p._decode_options(4)171 self.assertFalse(p._use_floating_point_rounding)172 self.assertTrue(p._use_hash_table)173 self.assertFalse(p._use_compression)174 self.assertFalse(p._is_index)175 p._decode_options(5)176 self.assertFalse(p._use_floating_point_rounding)177 self.assertTrue(p._use_hash_table)178 self.assertFalse(p._use_compression)179 self.assertTrue(p._is_index)180 p._decode_options(6)181 self.assertFalse(p._use_floating_point_rounding)182 self.assertTrue(p._use_hash_table)183 self.assertTrue(p._use_compression)184 self.assertFalse(p._is_index)185 p._decode_options(7)186 self.assertFalse(p._use_floating_point_rounding)187 self.assertTrue(p._use_hash_table)188 self.assertTrue(p._use_compression)189 self.assertTrue(p._is_index)190 p._decode_options(8)191 self.assertTrue(p._use_floating_point_rounding)192 self.assertFalse(p._use_hash_table)193 self.assertFalse(p._use_compression)194 self.assertFalse(p._is_index)195 p._decode_options(9)196 self.assertTrue(p._use_floating_point_rounding)197 self.assertFalse(p._use_hash_table)198 self.assertFalse(p._use_compression)199 self.assertTrue(p._is_index)200 p._decode_options(10)201 self.assertTrue(p._use_floating_point_rounding)202 self.assertFalse(p._use_hash_table)203 self.assertTrue(p._use_compression)204 self.assertFalse(p._is_index)205 p._decode_options(11)206 self.assertTrue(p._use_floating_point_rounding)207 self.assertFalse(p._use_hash_table)208 self.assertTrue(p._use_compression)209 self.assertTrue(p._is_index)210 p._decode_options(12)211 self.assertTrue(p._use_floating_point_rounding)212 self.assertTrue(p._use_hash_table)213 self.assertFalse(p._use_compression)214 self.assertFalse(p._is_index)215 p._decode_options(13)216 self.assertTrue(p._use_floating_point_rounding)217 self.assertTrue(p._use_hash_table)218 self.assertFalse(p._use_compression)219 self.assertTrue(p._is_index)220 p._decode_options(14)221 self.assertTrue(p._use_floating_point_rounding)222 self.assertTrue(p._use_hash_table)223 self.assertTrue(p._use_compression)224 self.assertFalse(p._is_index)225 p._decode_options(15)226 self.assertTrue(p._use_floating_point_rounding)227 self.assertTrue(p._use_hash_table)228 self.assertTrue(p._use_compression)229 self.assertTrue(p._is_index)230 return231if __name__ == '__main__':...
sensor.py
Source:sensor.py
1import logging2from .const import DOMAIN3from homeassistant.const import STATE_UNKNOWN4from homeassistant.helpers.update_coordinator import CoordinatorEntity5_LOGGER = logging.getLogger(__name__)6async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):7 sensors = []8 coordinator = hass.data[DOMAIN]9 for exchange, stocks in discovery_info["stocks"].items():10 for stock in stocks:11 sensors.append(StockSensor(coordinator, exchange + stock))12 async_add_devices(sensors, True)13class StockSensor(CoordinatorEntity):14 def __init__(self, coordinator, stock):15 super().__init__(coordinator)16 self._coordinator = coordinator17 self._stock = stock18 self._unique_id = f"{DOMAIN}.stock_{stock}"19 self.entity_id = self._unique_id20 self._is_index = (stock[0:2] == "sh" and stock[2:5] == "000") or (stock[0:2] == "sz" and stock[2:5] == "399")21 def get_value(self, key):22 if self._coordinator.data is not None and self._coordinator.data.get(self._stock) is not None:23 return self._coordinator.data.get(self._stock).get(key)24 else:25 return STATE_UNKNOWN26 @staticmethod27 def sign(str_val):28 if str_val != STATE_UNKNOWN and float(str_val) != 0 and str_val[0:1] != "-":29 return "+" + str_val30 return str_val31 @property32 def should_poll(self):33 return False34 @property35 def name(self):36 return f"{self.get_value('name')}({self._stock}) [{self.sign(self.get_value('涨è·'))}" \37 f"({self.sign(self.get_value('涨è·(%)'))}%)]"38 @property39 def unique_id(self):40 return self._unique_id41 @property42 def state(self):43 _state = self.get_value('å½åä»·æ ¼')44 if _state != STATE_UNKNOWN:45 return float(self.get_value('å½åä»·æ ¼'))46 else:47 return _state48 @property49 def extra_state_attributes(self) -> dict:50 ret = {51 "è¡ç¥¨ä»£ç ": self.get_value("è¡ç¥¨ä»£ç "),52 "å½åä»·æ ¼": self.get_value("å½åä»·æ ¼"),53 "æ¨æ¶": self.get_value("æ¨æ¶"),54 "ä»å¼": self.get_value("ä»å¼"),55 "æ交é": self.get_value("æ交é(æ)"),56 "å¤ç": self.get_value("å¤ç"),57 "å
ç": self.get_value("å
ç"),58 "涨è·": self.sign(self.get_value("涨è·")),59 "涨è·å¹
": self.sign(self.get_value("涨è·(%)")) + "%",60 "æé«": self.get_value("æé«"),61 "æä½": self.get_value("æä½"),62 "æ交é¢": self.get_value("æ交é¢(ä¸)"),63 "æ¯å¹
": self.get_value("æ¯å¹
") + "%",64 }65 if not self._is_index:66 ret.update({67 "åäº(" + self.get_value("åäº") + ")": self.get_value("åäºé(æ)"),68 "åå(" + self.get_value("åå") + ")": self.get_value("ååé(æ)"),69 "åä¸(" + self.get_value("åä¸") + ")": self.get_value("åä¸é(æ)"),70 "åäº(" + self.get_value("åäº") + ")": self.get_value("åäºé(æ)"),71 "åä¸(" + self.get_value("åä¸") + ")": self.get_value("åä¸é(æ)"),72 "ä¹°ä¸(" + self.get_value("ä¹°ä¸") + ")": self.get_value("ä¹°ä¸é(æ)"),73 "ä¹°äº(" + self.get_value("ä¹°äº") + ")": self.get_value("ä¹°äºé(æ)"),74 "ä¹°ä¸(" + self.get_value("ä¹°ä¸") + ")": self.get_value("ä¹°ä¸é(æ)"),75 "ä¹°å(" + self.get_value("ä¹°å") + ")": self.get_value("ä¹°åé(æ)"),76 "ä¹°äº(" + self.get_value("ä¹°äº") + ")": self.get_value("ä¹°äºé(æ)"),77 "æ¢æç": self.get_value("æ¢æç") + "%",78 "å¸çç": self.get_value("å¸çç"),79 "æµéå¸å¼": self.get_value("æµéå¸å¼"),80 "æ»å¸å¼": self.get_value("æ»å¸å¼"),81 "å¸åç": self.get_value("å¸åç"),82 "éæ¯": self.get_value("éæ¯"),83 "åä»·": self.get_value("åä»·"),84 "涨åä»·": self.get_value("涨åä»·"),85 "è·åä»·": self.get_value("è·åä»·"),86 "å§å·®": self.get_value("å§å·®"),87 "å¸ç(å¨)": self.get_value("å¸ç(å¨)"),88 "å¸ç(é)": self.get_value("å¸ç(é)")89 })90 return ret91 @property92 def unit_of_measurement(self):93 if self._is_index:94 return "ç¹"95 else:96 return "å
"97 @property98 def icon(self):...
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!!