Best Python code snippet using avocado_python
troll_api.py
Source:troll_api.py
...21 self._key_api = key_api22 self._url_to_server = url_to_server23 self._treshold = treshold24 25 def _save_to_json(self, response, path_to_save):26 """СоÑ
Ñанение даннÑÑ
полÑÑенного оÑвеÑа в Ñайл27 Args:28 response (dict): ÑоÑ
ÑанÑемÑе даннÑе29 path_to_save (str): пÑÑÑ Ð´Ð¾ ÑоÑ
ÑанÑемого Ñайла30 """31 with open(path_to_save, "w", encoding="utf-8") as write_file:32 json.dump(response, write_file, indent=2, ensure_ascii=False)33 def set_treshold(self, treshold):34 """ÐеÑод Ð´Ð»Ñ Ð·Ð°Ð´Ð°Ð½Ð¸Ñ Ð¿Ð¾Ñога оÑÑеÑÐµÐ½Ð¸Ñ ÑÑоллинга, пÑи авÑомаÑиÑеÑкой модеÑаÑии35 Args:36 treshold (float): поÑога оÑÑеÑÐµÐ½Ð¸Ñ ÑÑоллинга37 """38 self._treshold = treshold39 def get_count_available_requests(self,40 save_to_json=False, 41 path_to_save="available_requests_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")),42 timeout=300):43 """ÐеÑод Ð´Ð»Ñ Ð¾Ð¿ÑÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ Ð´Ð¾ÑÑÑпного колиÑеÑÑва запÑоÑов полÑзоваÑелÑ44 Args:45 save_to_json (bool): ÑоÑ
Ñанение полÑÑенной инÑоÑмаÑии в Ñайл. Defaults to False.46 path_to_save (str): пÑÑÑ Ð´Ð¾ ÑоÑ
ÑанÑемого Ñайла. Defaults to "available_requests_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")).47 timeout (int): макÑималÑное вÑÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¾ÑвеÑа Ð¾Ñ ÑеÑвеÑа, Ñек. Defaults to 300.48 Returns:49 dict: паÑамеÑÑÑ Ð´Ð¾ÑÑÑпнÑÑ
запÑоÑов Ð´Ð»Ñ Ð¿Ð¾Ð»ÑзоваÑелÑ50 """51 answer = requests.post(52 self._url_to_server + "/get_query_left", 53 data=json.dumps({"key_api":self._key_api}), 54 headers=self._headers,55 )56 response = answer.json()57 if save_to_json: self._save_to_json(response, path_to_save)58 return response59 60 def get_available_type_parsers(self,61 save_to_json=False, 62 path_to_save="available_parsers_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")),63 timeout=300):64 """ÐеÑод Ð´Ð»Ñ Ð¾Ð¿ÑÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ Ð´Ð¾ÑÑÑпного колиÑеÑÑва запÑоÑов полÑзоваÑелÑ65 Args:66 save_to_json (bool): ÑоÑ
Ñанение полÑÑенной инÑоÑмаÑии в Ñайл. Defaults to False.67 path_to_save (str): пÑÑÑ Ð´Ð¾ ÑоÑ
ÑанÑемого Ñайла. Defaults to "available_parsers_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")).68 timeout (int): макÑималÑное вÑÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¾ÑвеÑа Ð¾Ñ ÑеÑвеÑа, Ñек. Defaults to 300.69 Returns:70 dict: паÑамеÑÑÑ Ð´Ð¾ÑÑÑпнÑÑ
Ñипов паÑÑеÑов Ð´Ð»Ñ Ð¿Ð¾ÑÑалов71 """72 answer = requests.post(73 self._url_to_server + "/get_available_parsers", 74 data=json.dumps({"key_api":self._key_api}),75 headers=self._headers,76 )77 response = answer.json()78 if save_to_json: self._save_to_json(response, path_to_save)79 return response80 def get_proba(self, 81 question,82 answer, 83 save_to_json=False, 84 path_to_save="request_proba_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")),85 timeout=300):86 """ФоÑмиÑование запÑоÑа на ÑеÑÐ²ÐµÑ Ð¸ полÑÑение даннÑÑ
о веÑоÑÑноÑÑи ÑÑоллинга пÑи оÑвеÑе на вопÑоÑ87 Args:88 question (str, list): [description]89 answer (str, list): [description]90 save_to_json (bool): ÑоÑ
Ñанение полÑÑенной инÑоÑмаÑии в Ñайл. Defaults to False.91 path_to_save (str): пÑÑÑ Ð´Ð¾ ÑоÑ
ÑанÑемого Ñайла. Defaults to "request_proba_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")).92 timeout (int): макÑималÑное вÑÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¾ÑвеÑа Ð¾Ñ ÑеÑвеÑа, Ñек. Defaults to 300.93 Returns:94 dict: даннÑе о веÑоÑÑноÑÑи ÑÑоллинга пÑи оÑвеÑе на вопÑоÑ95 """96 answer = requests.post(97 self._url_to_server + "/get_proba", 98 data=json.dumps({99 "question":question,100 "answer":answer,101 "treshold":self._treshold,102 "key_api":self._key_api103 }), 104 headers=self._headers,105 timeout=timeout106 )107 response = answer.json()108 if save_to_json: self._save_to_json(response, path_to_save)109 return response110 def get_proba_from_link(self, 111 link,112 type_parser="answers_mail.ru", 113 save_to_json=False, 114 path_to_save="request_proba_from_link_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")),115 timeout=300):116 """ФоÑмиÑование запÑоÑа на ÑеÑÐ²ÐµÑ Ð¸ полÑÑение даннÑÑ
о веÑоÑÑноÑÑи ÑÑоллинга пÑи оÑвеÑе на вопÑÐ¾Ñ Ð¿Ð¾ ÑÑлÑке на поÑÑ Ð¿Ð¾ÑÑала117 Args:118 link ([type]): ÑÑÑлка на поÑÑ Ð¿Ð¾ÑÑала119 type_parser (str): вÑÐ±Ð¾Ñ Ñипа паÑÑеÑа Ð´Ð»Ñ Ð¸Ð·Ð²Ð»ÐµÑÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½ÑÑ
Ñ Ð¿Ð¾ÑÑа поÑÑала. Defaults to "answers_mail.ru".120 save_to_json (bool): ÑоÑ
Ñанение полÑÑенной инÑоÑмаÑии в Ñайл. Defaults to False.121 path_to_save (str): пÑÑÑ Ð´Ð¾ ÑоÑ
ÑанÑемого Ñайла. Defaults to "request_proba_from_link_{}.json".format(datetime.today().strftime("%Y-%m-%d_%H.%M.%S")).122 timeout (int): макÑималÑное вÑÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¾ÑвеÑа Ð¾Ñ ÑеÑвеÑа, Ñек. Defaults to 300.123 Returns:124 dict: даннÑе о веÑоÑÑноÑÑи ÑÑоллинга пÑи оÑвеÑе на вопÑоÑ125 """126 answer = requests.post(127 self._url_to_server + "/get_link", 128 data=json.dumps({129 "link":link,130 "parser":type_parser,131 "treshold":self._treshold,132 "key_api":self._key_api133 }), 134 headers=self._headers,135 timeout=timeout136 )137 response = answer.json()138 if save_to_json: self._save_to_json(response, path_to_save)139 return response140if __name__ == "__main__":141 api = FindTrollApi(key_api="qwerty")142 N = 7143 question = ["questionquestion"] * N144 answer = "answer"145 link = "1234567"146 t1 = time()147 data_ = api.get_proba(question, answer, save_to_json=True)148 print(time()-t1)149 """150 data1 = {151 "question":["questionquestion"]*N,152 "answer":"answer",...
test_main.py
Source:test_main.py
...128 with open(filename, "r") as json_data:129 data = json.load(json_data)130 return data131 @staticmethod132 def _save_to_json(filename, data) -> bool:133 with open(filename, "w") as json_file:134 json.dump(data, json_file, indent=2)135 return True136 def _return_accuracy_from_test(self) -> float:137 vocab_filename = "vocabulary.json"138 vocab = VocabularyCreator(self.train, vocab_filename)139 vocab.create_vocab()140 renege = RENEGE(self.train)141 if not renege.classify_emails():142 raise RuntimeError("Error classify emails")143 evaluation = evaluate(self.test)144 return evaluation["accuracy"]145 def get_accuracy_delta(self):146 return abs(self.initial_acc - self.new_acc)147 @staticmethod148 def _shuffle_email_words(email):149 for mail in email:150 split_table = mail["mail"]["Body"].split()151 random.shuffle(split_table)152 mail["mail"]["Body"] = ' '.join(split_table)153 return email154 @staticmethod155 def _add_noise(email):156 #TODO157 pass158 def test1(self):159 trainset = self._load_json("train_set.json")["dataset"]160 random.shuffle(trainset)161 self.train = "train700_mails.json"162 self._save_to_json(filename=self.train, data={"dataset": trainset})163 self.new_acc = self._return_accuracy_from_test()164 self.assertLessEqual(165 self.get_accuracy_delta(),166 self.THRESHOLD,167 "Le changement d'ordre des emails modifie l'accuracy de beaucoup.",168 )169 def test2(self):170 test_set = self._load_json("test_set.json")["dataset"]171 random.shuffle(test_set)172 self.test = "test300_mails.json"173 self._save_to_json(self.test, {"dataset": test_set})174 self.new_acc = self._return_accuracy_from_test()175 self.assertLessEqual(176 self.get_accuracy_delta(),177 self.THRESHOLD,178 "Le changement d'ordre des emails dans le testset modifie modifie l'accuracy de beaucoup.",179 )180 def test3(self):181 #Changement d'orde des mots dans train dataset182 test_set = self._load_json("train_set.json")["dataset"]183 shuffled_emails_words = self._shuffle_email_words(test_set)184 self.train = "train700_words.json"185 self._save_to_json(self.train, {"dataset": shuffled_emails_words})186 self.new_acc = self._return_accuracy_from_test()187 self.assertLessEqual(188 self.get_accuracy_delta(),189 self.THRESHOLD,190 )191 def test4(self):192 test_set = self._load_json("test_set.json")["dataset"]193 shuffled_emails_words = self._shuffle_email_words(test_set)194 self.test = "test300_words.json"195 self._save_to_json(self.test, {"dataset": shuffled_emails_words})196 self.new_acc = self._return_accuracy_from_test()197 self.assertLessEqual(198 self.get_accuracy_delta(),199 self.THRESHOLD,200 "Le changement d'ordre des mots dans le 'test dataset' modifie l'accuracy de beaucoup.",201 )202 def test5(self):203 #Ajout des memes email dans train dataset204 self.train = "train700x2.json"205 self.new_acc = self._return_accuracy_from_test()206 self.assertLessEqual(207 self.get_accuracy_delta(),208 self.THRESHOLD,209 )210 def test6(self):211 #Ajout des memes email dans test dataset212 self.test = "test300x2.json"213 self.new_acc = self._return_accuracy_from_test()214 self.assertLessEqual(215 self.get_accuracy_delta(),216 self.THRESHOLD,217 )218 def test7(self):219 #Bruit dans train dataset220 test_set = self._load_json("train_set.json")["dataset"]221 noised_emails_words = self._add_noise(test_set)222 self.train = "train700_noise.json"223 self._save_to_json(self.train, {"dataset": noised_emails_words})224 self.new_acc = self._return_accuracy_from_test()225 self.assertLessEqual(226 self.get_accuracy_delta(),227 self.THRESHOLD,228 )229 def test8(self):230 #Bruit dans test dataset231 test_set = self._load_json("test_set.json")["dataset"]232 noised_emails_words = self._add_noise(test_set)233 self.test = "test300_noise.json"234 self._save_to_json(self.test, {"dataset": noised_emails_words})235 self.new_acc = self._return_accuracy_from_test()236 self.assertLessEqual(237 self.get_accuracy_delta(),238 self.THRESHOLD,...
main.py
Source:main.py
...54 logger.info("get all public channels.")55 channels = get_all_public_channels()56 channel_path = base_path / "channel_master.json"57 logger.info(f"save all public channels. path: {channel_path}")58 _save_to_json(channels, channel_path)59 return channels60def _get_users(base_path: Path) -> List[Dict[str, Any]]:61 """62 å
¨ã¦ã®ã¦ã¼ã¶æ
å ±ãåå¾63 Parameters64 ----------65 base_path : Path66 åºåå
ã®Baseã¨ãªãPath67 Returns68 -------69 List[Dict[str, Any]]70 å
¨ã¦ã®ã¦ã¼ã¶æ
å ±71 """72 logger.info("get all users.")73 users = get_all_users()74 users_path = base_path / "user_master.json"75 logger.info(f"save all users. path: {users_path}")76 _save_to_json(users, users_path)77 return users78def _get_channel_message(base_path: Path, channel_id: str, channel_name: str) -> None:79 """80 ãã£ã³ãã«æ
å ±ãåå¾81 NOTE: å
¨ã¦ã¡ã¢ãªã«ä¹ããããã¡ã¢ãªä¸è¶³ã«æ³¨æ82 Parameters83 ----------84 base_path : Path85 åºåå
ã®Baseã¨ãªãPath86 channel_id : str87 ãã£ã³ãã«ID88 channel_name : str89 ãã£ã³ãã«å90 """91 channel_info = f"id:{channel_id}, name: {channel_name}"92 logger.info(f"get channel_message. {channel_info}")93 messages = get_channel_message(channel_id)94 messages_path = base_path / channel_id95 messages_path.mkdir()96 channel_message_path = messages_path / "nomal_messages.json"97 logger.info(f"save channel message. {channel_info}, path: {channel_message_path}")98 _save_to_json(messages, channel_message_path) # type: ignore99 logger.info(f"get replies_message. {channel_info}")100 for message in messages:101 _get_replies(messages_path, message, channel_id, channel_info)102def _get_replies(103 base_path: Path, message: Dict[str, Any], channel_id: str, channel_info: str104) -> None:105 """106 ãªãã©ã¤ã¡ãã»ã¼ã¸ãåå¾107 Parameters108 ----------109 base_path : Path110 åºåå
ã®Baseã¨ãªãPath111 message : Dict[str, Any]112 ã¡ãã»ã¼ã¸æ
å ±113 channel_id : str114 ãã£ã³ãã«ID115 channel_info : str116 ãã£ã³ãã«æ
å ±117 """118 replies = get_replies(channel_id, message)119 if replies:120 # NOTE: '1638883139.000600' ã®ããã«ã.ããå
¥ãã¨ãã¡ã¤ã«åã¨ãã¦ä¸é©æ ¼ãªã®ã§ã_ãã«ç½®æ121 thread_ts = message["thread_ts"].replace(".", "_")122 replies_path = base_path / f"{thread_ts}.json"123 logger.info(f"save replies message. {channel_info}, path: {replies_path}")124 _save_to_json(replies, replies_path) # type: ignore125def _save_to_json(data: Any, path: Path) -> Path:126 """127 jsonå½¢å¼ã§ä¿åãã128 Parameters129 ----------130 data : Any131 ä¿å対象ã®ãã¼ã¿132 path : Path133 ä¿åå
134 Returns135 -------136 Path137 ä¿åãããPath138 """139 with open(path, "w") as f:...
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!!