How to use _save_to_json method in avocado

Best Python code snippet using avocado_python

troll_api.py

Source:troll_api.py Github

copy

Full Screen

...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",...

Full Screen

Full Screen

test_main.py

Source:test_main.py Github

copy

Full Screen

...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,...

Full Screen

Full Screen

main.py

Source:main.py Github

copy

Full Screen

...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:...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run avocado automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful