Best Python code snippet using toolium_python
job.py
Source:job.py
1#!/usr/bin/python2# -*- coding: UTF-8 -*-3import re4import time5from datetime import timedelta, timezone, datetime6from random import randint7from re import Pattern8from requests import session, Response, Session9from notifier import Notifier10shanghai_tz = timezone(timedelta(hours=8), name='Asia/Shanghai')11def get_current_hour() -> int:12 now = datetime.utcnow().replace(tzinfo=timezone.utc)13 return now.astimezone(shanghai_tz).hour14class Job:15 _login_header: dict = {16 'Content-Type': 'application/x-www-form-urlencoded',17 'Host': 'pass.neu.edu.cn',18 'Origin': 'https://pass.neu.edu.cn',19 }20 _init_url: str = 'https://e-report.neu.edu.cn/login'21 _service_url: str = 'https://e-report.neu.edu.cn/notes/create'22 _update_info_url: str = 'https://e-report.neu.edu.cn/api/notes'23 _feedback_url: str = "https://e-report.neu.edu.cn/notes"24 _lt_matcher: Pattern = re.compile(r'name="lt" value="(.+?)"')25 _login_path_matcher: Pattern = re.compile(r'id="loginForm" action="(.+?)"')26 _token_matcher: Pattern = re.compile(r'name="_token" value="(.+?)"')27 _name_matcher: Pattern = re.compile(r'å½åç¨æ·ï¼(.+?) <span')28 _class_matcher: Pattern = re.compile(r'"suoshubanji":"(.+?)"')29 _date_matcher: Pattern = re.compile(r'"created_on":"(.+?)"')30 _wrong_auth: str = 'è´¦å·æå¯ç é误'31 _bad_info: str = 'ä¿¡æ¯è·å失败'32 _bad_init_login: str = 'è·åç»éä¿¡æ¯å¤±è´¥'33 def __init__(self, username: str, password: str, ip: str = ''):34 self._username: str = username35 self._password: str = password36 self._ip: str = ip37 self._client: Session = session()38 # è·åå°çè·¨æ¥éª¤å
±ç¨ä¸é´ä¿¡æ¯39 self._token: str = ""40 self._name: str = ""41 self._lt = ""42 self._login_path: str = ""43 self._class: str = ""44 self._date: str = ""45 @property46 def _login_body(self) -> str:47 return f'rsa={self._username}{self._password}{self._lt}&ul={len(self._username)}&pl={len(self._password)}<={self._lt}&execution=e1s1&_eventId=submit'48 @property49 def _login_url(self) -> str:50 return f'https://pass.neu.edu.cn{self._login_path}'51 @property52 def _update_info_body(self) -> str:53 return f'_token={self._token}&jibenxinxi_shifoubenrenshangbao=1&profile%5Bxuegonghao%5D={self._username}&profile%5Bsuoshubanji%5D={self._class}&jiankangxinxi_muqianshentizhuangkuang=%E6%AD%A3%E5%B8%B8&xingchengxinxi_weizhishifouyoubianhua=0&qitashixiang_qitaxuyaoshuomingdeshixiang='54 @property55 def _update_info_header(self) -> dict:56 h = {57 'Content-Type': 'application/x-www-form-urlencoded',58 'Host': 'e-report.neu.edu.cn',59 'Origin': 'https://e-report.neu.edu.cn',60 }61 if len(self._ip) > 0:62 h['X-Forwarded-For'] = self._ip63 return h64 @property65 def _info_url(self) -> str:66 return f'https://e-report.neu.edu.cn/api/profiles/{self._username}?xingming={self._name}'67 @property68 def _body_temperature(self) -> float:69 return 36 + randint(4, 7) / 1070 @property71 def _report_body_temperature_url(self) -> str:72 hour = get_current_hour()73 item_id = 1 if 7 <= hour <= 9 else 2 if 12 <= hour <= 14 else 374 return f'https://e-report.neu.edu.cn/inspection/items/{item_id}/records'75 @property76 def _report_body_temperature_body(self) -> str:77 return f'_token={self._token}&temperature={self._body_temperature}&suspicious_respiratory_symptoms=0&symptom_descriptions='78 @staticmethod79 def _is_login_success(resp: Response) -> bool:80 return resp.url.startswith("https://e-report.neu.edu.cn")81 # property ä¸å¥½ç82 def _is_reported(self) -> bool:83 return self._date == time.strftime(r'%Y-%m-%d', time.localtime())84 @staticmethod85 def _unexpected_exception(error: Exception = None) -> str:86 return f'ç½ç»é误æå
¶ä»é误\n{error}'87 def _login(self) -> (bool, str):88 try:89 resp: Response = self._client.get(self._init_url)90 lt: list = self._lt_matcher.findall(resp.text)91 lp: list = self._login_path_matcher.findall(resp.text)92 if len(lt) < 1 or len(lp) < 1:93 return False, self._bad_init_login94 self._lt = lt[0]95 self._login_path = lp[0]96 resp: Response = self._client.post(self._login_url, data=self._login_body, headers=self._login_header)97 if self._is_login_success(resp):98 return True, ''99 return False, self._wrong_auth100 except Exception as e:101 return False, self._unexpected_exception(e)102 def _login_service(self) -> (bool, str):103 try:104 resp: Response = self._client.get(self._service_url)105 self._token = self._token_matcher.findall(resp.text)[0]106 self._name = self._name_matcher.findall(resp.text)[0]107 return True, ''108 except Exception as e:109 return False, self._unexpected_exception(e)110 def _get_info(self) -> (bool, str):111 try:112 resp: Response = self._client.get(self._info_url)113 if resp.text.find(self._username) == -1:114 return False, self._bad_info115 date = self._date_matcher.findall(resp.text)116 klass = self._class_matcher.findall(resp.text)117 if len(date) < 1 or len(klass) < 1:118 return False, self._bad_info119 self._date = date[0]120 self._class = klass[0]121 return True, ''122 except Exception as e:123 return False, self._unexpected_exception(e)124 def _update_info(self) -> (bool, str):125 try:126 resp: Response = self._client.post(self._update_info_url, data=self._update_info_body,127 headers=self._update_info_header)128 if resp.status_code == 201:129 return True, ""130 return False, resp.text131 except Exception as e:132 return False, self._unexpected_exception(e)133 def _report_body_temperature(self):134 try:135 resp: Response = self._client.post(self._report_body_temperature_url,136 data=self._report_body_temperature_body,137 headers=self._update_info_header)138 print(resp.status_code)139 if resp.status_code == 200:140 return True, ""141 return False, resp.text142 except Exception as e:143 return False, self._unexpected_exception(e)144 def do(self, notifier: Notifier):145 today = time.strftime('%m/%d/%Y')146 # ç»é147 success, msg = self._login()148 if not success:149 notifier.send(f"{today} ä¸å¥½ææåï¼ç»é失败äºå¢ï¼", msg)150 return151 # è¿å
¥å¹³å°152 success, msg = self._login_service()153 if not success:154 notifier.send(f"{today} ä¸å¥½ææåï¼é´æ失败å¢ï¼", msg)155 return156 # è·åä¿¡æ¯157 success, msg = self._get_info()158 if not success:159 notifier.send(f"{today} ä¸å¥½ææåï¼è·åå·²æä¿¡æ¯å¤±è´¥ï¼", msg)160 return161 # æ¯å¦ä»æ¥æç¾å°è¿162 if not self._is_reported():163 # æå¡164 success, msg = self._update_info()165 if not success:166 notifier.send(f"{today} ååï¼æå¡å¤±è´¥äºæï¼", msg)167 return168 notifier.send(f"{today} 好è¶ï¼æå¡æåï¼", "I'm fine, thank you.ï¼ä»ä¹çå±çå½¢å¼ä¸»ä¹ï¼è¯·é®é¢å¯¼æ¨è½æ¯å¤©æå¡åï¼ï¼")169 # ä¸æ¥ä½æ¸©170 success, msg = self._report_body_temperature()171 if not success:172 notifier.send(f"{today} ååï¼ä¸æ¥ä½æ¸©å¤±è´¥", msg)173 return...
dates.py
Source:dates.py
1"""Grammar for extracting possible dates from running tests"""2import string3import pynini4from pynini.lib import byte, pynutil, rewrite5def _possibly_zero_padded(top: int):6 """Adds optional leading '0' to single-digit numbers in a range7 Args:8 top: top of the range9 Returns:10 an FST representing number from 1 to top inclusive11 """12 nums = [str(d) for d in range(1, top + 1)]13 nums = [f"{d:02d}" for d in range(1, top + 1)] + nums14 return pynini.union(*nums).optimize()15_lowercase = pynini.union(16 *[pynini.cross(x.upper(), x) for x in string.ascii_lowercase]17).closure()18_sigma_star = pynini.closure(byte.BYTE)19_tolower = pynini.cdrewrite(_lowercase, "", "", _sigma_star)20_month_map = [21 ["1", ["january", "jan", "jan."]],22 ["2", ["february", "feb", "feb."]],23 ["3", ["march", "mar", "mar."]],24 ["4", ["april", "apr", "apr."]],25 ["5", ["may"]],26 ["6", ["june", "jun", "jun."]],27 ["7", ["july", "jul", "jul."]],28 ["8", ["august", "aug", "aug."]],29 ["9", ["september", "sept", "sept", "sep", "sep."]],30 ["10", ["october", "oct", "oct."]],31 ["11", ["november", "nov", "nov."]],32 ["12", ["december", "dec", "dec."]],33]34# *x[1] define list35_month_names = pynini.union(36 *(pynini.cross(pynini.union(*x[1]), x[0]) for x in _month_map)37).optimize()38_month_nums = pynini.union(*(m[0] for m in _month_map)).optimize()39_space = pynini.accep(" ") ** (1, ...)40# TODO(rws): make these match for months41_day_nums = _possibly_zero_padded(31)42_four_etc = pynini.union("4", "5", "6", "7", "8", "9", "0")43_day_ordinal = (44 (_day_nums @ (_sigma_star + "1")) + pynutil.delete("st")45 | (_day_nums @ (_sigma_star + "2")) + pynutil.delete("nd")46 | (_day_nums @ (_sigma_star + "3")) + pynutil.delete("rd")47 | (_day_nums @ (_sigma_star + _four_etc)) + pynutil.delete("th").optimize()48)49_digit = [str(d) for d in range(10)]50_digit_no_zero = [str(d) for d in range(1, 10)]51# negative weight on year favors picking a longer include a year rather than just month and day, if a possible year is present.52_year = pynutil.add_weight(53 pynini.union(*_digit_no_zero) + pynini.union(*_digit) ** 3, -154).optimize()55def _markup(expr: pynini.FstLike, mark: str) -> pynini.Fst:56 """Introduces XML markup57 Args:58 expr: an FST59 mark: the name to apply to the region60 Returns:61 An FST mapping from expr to <mark>expr</mark>62 """63 markup = pynutil.insert(f"<{mark}>")64 markup.concat(expr)65 markup.concat(pynutil.insert(f"</{mark}>"))66 return markup.optimize()67_mdy_full_date = (68 _markup(_month_names, "month")69 + pynutil.delete(_space)70 + _markup(_day_nums, "day")71 + (pynutil.delete(",").ques + pynutil.delete(_space) + _markup(_year, "year")).ques72)73_mdy_full_date_ordinal = (74 _markup(_month_names, "month")75 + pynutil.delete(_space)76 + pynutil.delete("the" + _space)77 + _markup(_day_nums, "day")78 + (pynutil.delete(",").ques + pynutil.delete(_space) + _markup(_year, "year")).ques79)80_dmy_full_date = (81 _markup(_month_names, "day")82 + pynutil.delete(_space)83 + _markup(_day_nums, "month")84 + (pynutil.delete(",").ques + pynutil.delete(_space) + _markup(_year, "year")).ques85)86_dmy_full_date_ordinal = (87 pynutil.delete("the" + _space)88 + _markup(_month_names, "day")89 + pynutil.delete(_space)90 + pynutil.delete("of" + _space)91 + _markup(_day_nums, "month")92 + (pynutil.delete(",").ques + pynutil.delete(_space) + _markup(_year, "year")).ques93)94_numeric_ymd = (95 _markup(_year, "year")96 + pynutil.delete("/")97 + _markup(_month_names, "month")98 + pynutil.delete("/")99 + _markup(_day_nums, "day")100 + _markup(_year, "year")101)102_numeric_dmy = (103 _markup(_day_nums, "day")104 + pynutil.delete("/")105 + _markup(_month_nums, "month")106 + pynutil.delete("/")107 + _markup(_year, "year")108)109_month_year = (110 _markup(_month_names, "month") + pynutil.delete(_space) + _markup(_year, "year")111)112_date = (113 _mdy_full_date114 | _mdy_full_date_ordinal115 | _dmy_full_date116 | _dmy_full_date_ordinal117 | _numeric_ymd118 | _numeric_dmy119 | _month_year120)121# And wrap the whole thing with <date>.122_date = _markup(_date, "date")123# TODO: FST @ FST to continue FST124_date_matcher = (_tolower @ _date).optimize()125_date_tagger = pynini.cdrewrite(_date_matcher, "", "", _sigma_star).optimize()126def match(text: str) -> str:127 return rewrite.one_top_rewrite(text, _date_matcher)128def tag(text: str) -> str:129 # return rewrite.one_top_rewrite(text, _date_tagger)130 return pynini.shortestpath(pynini.compose(text, _date_tagger)).string()131if __name__ == "__main__":132 print(match("2/1/1985"))133 text = """I met John on June 1, 1985 in Colorado."""134 result = tag(text)...
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!!