def api_github_message(): """api for sending comments""" if request.headers['Content-Type'] == 'application/json': print('inside server ') my_info = json.dumps(request.json) payload = json.loads(my_info) if not payload['action'] == 'closed': model = StoreModel().loadData() tdf = TestData() tdf1 = TestData1() parameter_dict = tdf.fetcher(my_info) extension_file = tdf1.file_fetcher(my_info) feature_dict = parameter_dict['feature_dict'] comment_url = parameter_dict['comment_url'] comment_body = tdf.test_feeder(feature_dict, model) file_comment_body = tdf1.file_test_feeder(extension_file[0], extension_file[1]) Comment.post_comment(comment_url, comment_body) Comment.post_comment(comment_url, str(file_comment_body)) app.logger.info(comment_body) prediction_response = json.dumps({"state": comment_body}) app.logger.info(comment_body) res = Response(prediction_response, status=200, mimetype='application.json') return res prediction_response = json.dumps({"state": "closed pull request"}) app.logger.info("closed pull request") res = Response(prediction_response, status=200, mimetype='application.json') return res
def classify_data_item(self, data_item, decision_tree): """ Function that classifies a data item from test data set by traversing the trained decision tree. :param data_item: :param decision_tree: :return: """ test_data = TestData() current_node = decision_tree split_feature_value = data_item[current_node.split_feature_index] # Traverse tree until it finds the leaf node or the split on the feature value is not found. while len(current_node.children ) > 0 and split_feature_value in current_node.children: current_node = current_node.children[split_feature_value] split_feature_value = data_item[current_node.split_feature_index] classified = current_node.class_label test_data.predicted_class = classified test_data.is_error = True if data_item[0] != classified else False test_data.is_false_negative = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_true_negative = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_false_positive = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False test_data.is_true_positive = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False return test_data
def predict(*, path_csv, path_model, model_name, batch_size, device, transform): model = ConvnetModel(model_name).to(device) model_checkpoint = torch.load(path_model + ".pth.tar", map_location=lambda storage, loc: storage.cuda(0)) model.load_state_dict(model_checkpoint['state_dict']) data_loader_test = DataLoader( TestData(path_csv, transform=transform), batch_size=batch_size, shuffle=False, num_workers=0) model.eval() study_y = {} for (x, study) in data_loader_test: bs, n_crops, c, h, w = x.size() x = x.to(device) with torch.no_grad(): y = torch.nn.Sigmoid()(model(x.view(-1, c, h, w))) y = y.to(CPU) y = y.view(bs, n_crops) for i in range(bs): if study[i] in study_y: study_y[study[i]][0] += 1 study_y[study[i]][1] += y[i,:] else: study_y[study[i]] = [1, y[i,:]] lst = [] # arithmetic average for key, value in study_y.items(): lst.append([key] + (value[1] / value[0]).tolist()) return sorted(lst)
def submit_1to1_demo_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom1") demo_page = DemoPage(driver=chrome_browser) # Click 'Schedule Now' button on demo page demo_page.schedule_now_button.click() # Insert test data in required fields on registration form demo_page.first_name_input1.input_text(test_data.firstName) demo_page.last_name_input1.input_text(test_data.lastName) demo_page.company_name_input1.input_text(test_data.companyName) demo_page.business_email_input1.input_text(test_data.email) demo_page.phone_number_input.input_text(test_data.phone) demo_page.job_title_input.input_text(test_data.jobTitle) demo_page.company_type_select.select_by_value(test_data.companyType) demo_page.privacy_policy_checkbox.click() # Submit registration form demo_page.get_1to1_demo_button.click() # TEST -> That confirmation message is displayed, after submitting 1 to 1 demo request form assert EC.visibility_of_element_located(demo_page.confirmation_message1)
def request_feed_webview(self, num_items='all'): url = self.url_prefix + '/feed' data = {'StatusCode':200, 'num_items':num_items} total_time = Timer() response = requests.get(url=url, data=json.dumps(data), headers=self.auth_header) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def request_getter(self, command, filename=''): url = self.url_prefix + '/getter' data = {'StatusCode': 200, 'command': command} if filename is not '': data['filename'] = filename total_time = Timer() response = requests.get(url=url, data=json.dumps(data), headers=self.auth_header) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def test_incorrect_email(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.valid_password) rp.confirm_password(td.valid_password) rp.fill_email(td.invalid_email) rp.confirm_email(" ") ut.verify_visible_errors(1, ["Podaj prawidłowy adres email!"])
def test_wrong_password_during_confirmation(self, email, password): # Stworzenie instancji klasy RegistrationPage (rp) rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password("3") rp.fill_email(email) # UWAGA TEST! ut.verify_visible_errors(1, ["Hasło i potwierdzenie hasła muszą być takie same."])
def test_incorrect_birth_year(self): rp = RegistrationPage(self.driver) td = TestData() ut = VerifyErrors(self.driver) rp.fill_login(td.username) rp.fill_password(td.password) rp.confirm_password(td.password) rp.fill_email(td.valid_email) rp.confirm_email(td.valid_email) rp.fill_birth_year("18") rp.choose_gender_female() ut.verify_visible_errors(1, ["* Niepoprawny rok urodzenia"])
def predict(path_csv, config): cudnn.benchmark = True model = convnet_models.load( config["model_name"], input_size=config["crop_size"], pretrained=False ).to(GPU) model_checkpoint = torch.load(config["path_model"], map_location=lambda storage, loc: storage.cuda(0)) model.load_state_dict(model_checkpoint['state_dict']) data_loader_test = DataLoader( TestData(path_csv, transform=config["transform"].get( img_size=config["img_size"], crop_size=config["crop_size"], target_mean=config["target_mean"], target_std=config["target_std"] )), batch_size=config["batch_size"], shuffle=False, num_workers=2, pin_memory=True ) model.eval() study_y = {} with torch.no_grad(): for (x, study) in data_loader_test: bs, n_crops, c, h, w = x.size() x = x.to(GPU) y = model(x.view(-1, c, h, w)) y = y.view(bs, n_crops).mean(1) for i in range(bs): if study[i] in study_y: study_y[study[i]][0] += 1 study_y[study[i]][1] += y[i] else: study_y[study[i]] = [1, y[i]] lst = [] for key, value in study_y.items(): lst.append([key, value[1] / value[0]]) lst = sorted(lst) keys = [] result = np.zeros(len(lst)) for i in range(len(lst)): keys.append(lst[i][0]) result[i] = lst[i][1] return keys, result
def classify_data_item(self, data_item, learn_tree_list): """ Function that classifies a data item from test data set by traversing the trained decision tree. :param data_item: :param decision_tree: :return: """ result_dict = dict() test_data = TestData() # Iterating to all the learnt bag trees to find majority vote. for ltree in learn_tree_list: current_node = ltree.decision_tree split_feature_value = data_item[current_node.split_feature_index] # Traverse tree until it finds the leaf node or the split on the feature value is not found. while len(current_node.children ) > 0 and split_feature_value in current_node.children: current_node = current_node.children[split_feature_value] split_feature_value = data_item[ current_node.split_feature_index] if current_node.class_label not in result_dict: result_dict[current_node.class_label] = 1 else: result_dict[current_node.class_label] += 1 # Getting the majority vote here. classified = self.get_majority_vote(result_dict) test_data.predicted_class = classified test_data.is_error = True if data_item[0] != classified else False test_data.is_false_negative = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_true_negative = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.NEGATIVE_VALUE else False test_data.is_false_positive = True if data_item[0] == GlobalVectors.NEGATIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False test_data.is_true_positive = True if data_item[0] == GlobalVectors.POSITIVE_VALUE \ and classified == GlobalVectors.POSITIVE_VALUE else False return test_data
def submit_watch_now_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom2") demo_page = DemoPage(driver=chrome_browser) # Click 'Watch Now' button on demo page demo_page.watch_now_button.click() # Insert test data in required fields on registration form demo_page.first_name_input2.input_text(test_data.firstName) demo_page.last_name_input2.input_text(test_data.lastName) demo_page.company_name_input2.input_text(test_data.companyName) demo_page.business_email_input2.input_text(test_data.email) demo_page.privacy_policy_checkbox2.click() # Submit registration form demo_page.watch_now_demo_button.click() # TEST -> That confirmation message is displayed, after submitting watch now request form assert EC.visibility_of_element_located(demo_page.confirmation_message2)
def request_putter(self, image_path, filename): with open(image_path, mode='rb') as file: img = file.read() image_64_encode = base64.encodebytes(img).decode("utf-8") json_object = { "HTTPMethod":"POST", "StatusCode":200, "body": { "title":filename, "img":image_64_encode } } url = self.url_prefix + "/putter" data = json.dumps(json_object) headers = self.auth_header total_time = Timer() response = requests.post(url, data=data,headers=headers) total_time = total_time.__exit__() response_dict = self.insert_timing_for_called_lambda(resp=response, total_time=total_time) return TestData(complete_json=response_dict)
def main(): print(__file__ + " start!!") # simulation parameters nPoint = 1000 fieldLength = 50.0 motion = [0.5, 2.0, np.deg2rad(-10.0)] # movement [x[m],y[m],yaw[deg]] nsim = 3 # number of simulation for _ in range(nsim): # previous points td = TestData() p = td.nominal_input.sweep px = p[:,0] py = p[:,1] # px = (np.random.rand(nPoint) - 0.5) * fieldLength # py = (np.random.rand(nPoint) - 0.5) * fieldLength previous_points = np.vstack((px, py)) input_data = td.top_wall_input1 c = input_data.sweep cx = c[:,0] cy = c[:,1] # current points # cx = [math.cos(motion[2]) * x - math.sin(motion[2]) * y + motion[0] # for (x, y) in zip(px, py)] # cy = [math.sin(motion[2]) * x + math.cos(motion[2]) * y + motion[1] # for (x, y) in zip(px, py)] current_points = np.vstack((cx, cy)) R, T = icp_matching(previous_points, current_points) print("Calculated R:", R) print("Calculated T:", T) print("Real R: ", [[math.sin(input_data.theta), math.cos(input_data.theta)], [-math.cos(input_data.theta), math.sin(input_data.theta)]]) print("Real T: ", [input_data.y, -input_data.x])
def submit_sign_up_here_request(chrome_browser): # Load test data from json test_data = TestData("registrationFrom3") demo_page = DemoPage(driver=chrome_browser) # Click 'Sign Up Here' button on demo page demo_page.sign_up_here.click() # Insert test data in required fields on registration form demo_page.first_name_input3.input_text(test_data.firstName) demo_page.last_name_input3.input_text(test_data.lastName) demo_page.company_name_input3.input_text(test_data.companyName) demo_page.business_email_input3.input_text(test_data.email) demo_page.job_title_input3.input_text(test_data.jobTitle) demo_page.company_type_select3.select_by_value(test_data.companyType) demo_page.privacy_policy_checkbox3.click() # Submit registration form demo_page.save_my_spot_button3.click() # TEST -> That confirmation message is displayed, after submitting sign up form assert EC.visibility_of_element_located(demo_page.confirmation_message3)
def setUp(self): self.operator = TestData()
import heapq class Recommender: def __init__(self, train): self.train = train def vector_model(self,to_predict): cos = cosine_similarity(self.train,to_predict) return self.train[(heapq.nlargest(2,xrange(len(cos)),cos.take))[1:][0]] def fit(self): self.nbrs = NearestNeighbors(n_neighbors=10).fit(self.train) # choose the 5 nearest neighbors def predict(self, to_predict): indices,distances = self.getKNN(to_predict) return [self.train[i] for i in indices] def getKNN(self,to_predict): distances, indices = self.nbrs.kneighbors(test.reshape(1,-1) , n_neighbors=10) # but take only the closest return indices,distances # his is the proof that the best match is in the cluster if __name__ == '__main__': t = TestData() X, test = t.generateTrainData(3700,1000) knn = Recommender(X) knn.fit() print knn.predict(test) print knn.vector_model(test)
def setUp(self): self.test_data = TestData()