def GetRuleData(check_id, if_use_dao): ruleTableName = configs.table_name[0] filterInputRule = [] filterOutputRule = [] natPreRule = [] if if_use_dao == "1": # 从数据库中读取数据 print("读取数据库规则数据……") column = MysqlInterface.Get_Table_Column(configs.host, configs.username, configs.password, configs.database, ruleTableName) ruleRawData = MysqlInterface.Get_Raw_Data(configs.host, configs.username, configs.password, configs.database, check_id, ruleTableName, column) for oneRuleData in ruleRawData: if oneRuleData["_type"] == 1: filterInputRule.append(rule.rule().rawRuleFormat( oneRuleData["_order"], oneRuleData["content"])) elif oneRuleData["_type"] == 2: filterOutputRule.append(rule.rule().rawRuleFormat( oneRuleData["_order"], oneRuleData["content"])) elif oneRuleData["_type"] == 5: natPreRule.append(rule.rule().rawRuleFormat( oneRuleData["_order"], oneRuleData["content"])) return filterInputRule, filterOutputRule, natPreRule else: # 直接读取参数数据 pass return [], [], []
def testLocals(): # 创建 规则号 的组合 ruleNumList = [1, 2] listAll = [] for i in range(1, len(ruleNumList) + 1): iter = itertools.combinations(ruleNumList, i) listAll.append(list(iter)) # 根据 规则号组合 声明最终转化csv的变量 for inList in listAll: for brackets in inList: dfName = 'rule' for ruleNum in brackets: dfName = dfName + str(ruleNum) + '+' locals()[dfName] = pd.DataFrame() # 读取原始csv文件 df = pd.read_csv(con.csvPath + '603999.csv') # 根据原始csv文件生成筛选 true False class rule: num = 0 name = '' formula = '' ruleList = [] rule1 = rule() rule1.num = 1 rule1.name = 'jdk小于20' df[rule1.name] = (df['kdj_k'] < 20) & (df['kdj_d'] < 20) & (df['kdj_j'] < 20) rule2 = rule() rule2.num = 2 rule2.name = 'jdk大于0' df[rule2.name] = (df['kdj_k'] > 0) & (df['kdj_d'] > 0) & (df['kdj_j'] > 0) ruleList.append(rule1) ruleList.append(rule2) for inList in listAll: for brackets in inList: dfc = copy.deepcopy(df) dfName = 'rule' for ruleNum in brackets: dfName = dfName + str(ruleNum) + '+' for rule in ruleList: if (ruleNum == rule.num): dfc = dfc[dfc[rule.name] == True] if dfc.empty: continue locals()[dfName] = locals()[dfName].append(dfc) for inList in listAll: for brackets in inList: dfName = 'rule' for ruleNum in brackets: dfName = dfName + str(ruleNum) + '+' locals()[dfName].to_csv(dfName + '.csv')
def unvisited_children(node): newNode = [] # generate a list of moves. for item in rule(node): newNode.append(make_move(node, item)) if make_move( node, item) not in visited else 0 return newNode
def interact(w=None): if w: crud_helper = crud.crud("/Users/john/python_workspace/words/kb") r = rule.rule() m = dict.match(crud_helper,w["form"]["spelling"]) f = dict.filter(r,w) list(w) else: crud_helper = crud.crud("/Users/john/python_workspace/words/kb") is_edit = False is_review = False while(True): if (not w): is_edit = False is_review = True if (is_edit): print "#edit> ", elif(is_review): print "#review> ", else: print "#query> ", c = raw_input() if (is_edit): if (c == "q"): is_edit = False elif (c == "h"): usage2() elif (is_review): if (c == "q"): if (not w): break is_review = False if (c == "l"): crud_helper.list() else: if (c == "q"): break elif (c == "h"): usage() elif (c == "l"): list(w) elif (c == "a"): crud_helper.create(w) crud_helper.export("/Users/john/python_workspace/words/kb") break elif (c == "e"): is_edit = True elif (c == "r"): is_review = True elif (c == "c"): crud_helper.create(w) elif (c == "x"): crud_helper.export("/Users/john/python_workspace/words/kb") return ""
def build(rule_msg, is_mock=False): triggers = [] for trigger_msg in rule_msg.triggers: trigger = trigger_factory.build(trigger_msg, is_mock) triggers.append(trigger) actions = [] for action_msg in rule_msg.actions: action = action_factory.build(action_msg, is_mock) actions.append(action) rule_obj = rule.rule(triggers, actions) return rule_obj
def test_case24(self): self.airline_area = '国内' self.start = '国内' self.cabin_type = '经济舱' self.Ticket_type = '成人票' self.price = '1111' self.Baggage_list = ['重量:30 长:30 宽:30 高:140 特殊行李:是 类型:类型1 免费额:否'] r = rule(self.Baggage_list, self.airline_area, self.start, self.cabin_type, self.Ticket_type, self.price) result, dw = r.count_dollar() self.assertEqual(result, round(980))
def evolve (self): state = [] for dummy in range(0,self.sublistNum,1): temp = [] for dummy2 in range(0,self.sublistSize,1): temp += [0] state += [temp] for dummy in range(0,self.sublistNum,1): for dummy2 in range(0,self.sublistSize,1): state[dummy][dummy2] = [rule(self.list[dummy][dummy2]),getNeighbours(dummy,dummy2)] return true
def __init__(self): pygame.init() self.screen = pygame.display.set_mode(SCR_RECT.size) pygame.display.set_caption(u"Gomoku Narabe") self.font = pygame.font.SysFont(None, 16) self.field = [[EMPTY for x in range(NUM_COL)] for y in range(NUM_ROW)] self.generation = 0 # #self.run = False # シミュレーション実行中か? self.cursor = [NUM_COL/2, NUM_ROW/2] self.turn = WHITE #Fiest turn. It must be BLACK but WHITE works good, it should be isnpected self.rule = rule.rule(self.field) self.history = []
def idfs(queue, path, count, depth): # copy the last item in queue. node = deepcopy(queue[-1]) # check for prev moves. If so, return false print len(queue), "this is len q" if (len(queue) > 1): for i in range(len(queue) - 1): if (compare(node, queue[i])): path.pop() return False, count #check if solution found. if node.is_goal(): return path, count # Find legal move. rules = rule(node) if len(queue) > depth: print "path" return "depth", count while rules >= 0: count += 1 if len(rules) == 0: return "depth", count # update new board newN = deepcopy(node) print node.board, " this is board " newN.moves(rules[0]) queue.append(newN) # newNode = deepcopy(queue) # newNode.append(newN) # node.moves(rules[0]) # newNode = deepcopy(queue) # newNode.append(node) # add to path path.append(rules[0]) del rules[0] # call for result in new board. result, count = backtrack1(queue, path, count) # if false, try different path. if result == False: continue if result == "depth": return queue, path, count else: # if found, return result. return queue, path, count, "true"
def testCombo(): df = pd.read_csv(con.csvPath + '603999.csv') class rule: num = 0 name = '' formula = '' ruleList = [] rule1 = rule() rule1.num = 1 rule1.name = 'jdk小于20' rule1.formula = (df['kdj_k'] < 20) & (df['kdj_d'] < 20) & (df['kdj_j'] < 20) rule2 = rule() rule2.num = 2 rule2.name = 'jdk大于80' rule2.formula = (df['kdj_k'] > 0) & (df['kdj_d'] > 0) & (df['kdj_j'] > 0) ruleList.append(rule1) ruleList.append(rule2) ruleNumList = [1, 2] listAll = [] for i in range(1, len(ruleNumList) + 1): iter = itertools.combinations(ruleNumList, i) listAll.append(list(iter)) for inList in listAll: for brackets in inList: for ruleNum in brackets: for rule in ruleList: ruleCsvName = '' if (ruleNum == rule.num): ruleCsvName = ruleCsvName.__add__(rule.name) df[rule.name] = rule.formula df = df[df[rule.name] == True] # 输出到csv df.to_csv(con.csvPath + ruleCsvName + '.csv', index=False)
def evolve(self,rule): self.nextState = [[0 for i in range(self.sizeX)] for j in range(self.sizeY)] rows = self.sizeY cols = self.sizeX for i in range (0,rows): for j in range (0,cols): value = self.store[i][j] listinput = self.getNeighbours(i, j) result = rule(value, listinput) self.nextState[i][j] = result self.store = self.nextState
def point_rule(net, point, lim): x = net.shape[0] y = net.shape[1] for i in range(x): for j in range(y): if [i, j] in point: net[i, j] = rule.rule(net, i, j, 1, net[i, j], lim) if net[i, j] == lim: if net[i, j + 1] == 0: point.append([i, j + 1]) if net[i + 1, j] == 0: point.append([i + 1, j]) if net[i, j - 1] == 0: point.append([i, j - 1]) if net[i - 1, j] == 0: point.append([i - 1, j])
def run(self): result = [] _itemsets = filter(lambda x: len(x) > self.min_lhs, self.itemsets) if self.restrict_rhs: _itemsets = filter(lambda x: x.contains(self.restrict_rhs), _itemsets) for item in _itemsets: for lhs, rhs in item.combination(): if self.restrict_rhs: if any(np.isin(rhs, self.restrict_rhs)) == False: continue support = self.freq_dict[lhs] confidence = self.freq_dict[tuple(sorted(lhs + rhs))] / support if confidence > self.min_confidence: result.append(rule(lhs, rhs, support, confidence)) return result
def start_game(self): game_rule = rule(self.hole, self.user_name) wkl = worker_level(DB_URL) levels = wkl.get_by_id(self.user_id) distance_rule = golf_distance(self.hole) actions = [] start_action = game_rule.get_start_action() actions.append(start_action) cur_action = start_action next_action = "" count = 0 while next_action != "inhole": next_action = game_rule.get_next_action(levels, cur_action) actions.append(next_action) cur_action = next_action count += 1 if count > 20: break # Finish a hole score = self.get_score(actions) shots = [] totalDistance = 0 for i in range(len(actions) - 1): dist = distance_rule.get_distance(actions[i], actions[i+1]) totalDistance += dist shots.append({ "distance": round(dist,2), "toLocation": action_abbr[actions[i+1]], "score": 1, "action": action_abbr[actions[i]], "holeType": self.hole }) game_data = { "Level": levels, "Day": "Monday", "Shot": shots, "HoleScore": score, "totalDistance": totalDistance } saved_data = self.save_game(game_data) return saved_data
def rules_from_file(filename): line_num = 0 rule_file = open(filename, "r").readlines() terminals = [] rules = [] terminals = rule_file[0].split() line_num += 1 for line in rule_file[1:]: if not line: continue try: rules.append(rule.rule(line.strip())) line_num += 1 except: raise BadFileError("Rule file is invalid (line %d) '%s'" % (line_num, line)) return rules, terminals
def backtrack1(queue, path, count): # copy the last item in queue. node = deepcopy(queue[-1]) # check for prev moves. If so, return false if (len(queue) > 1): for i in range(len(queue) - 1): if (compare(node, queue[i])): path.pop() return False, count #check if solution found. if node.is_goal(): return path, count # Find legal move. rules = rule(node) if len(queue) > 2: return False, count while rules >= 0: count += 1 if len(rules) == 0: return False, count # update new board newN = deepcopy(node) newN.moves(rules[0]) newNode = deepcopy(queue) newNode.append(newN) # add to path path.append(rules[0]) del rules[0] # call for result in new board. result, count = backtrack1(newNode, path, count) # if false, try different path. if result == False: continue else: # if found, return result. return path, count
def getvalue(self): self.airline_value = self.airline.currentText() #航线区域类型 self.start_value = self.start.currentText() #始发航站 self.jicang_value = self.jicang.currentText() #机舱类型 self.kepiaotype_value = self.kepiaotype.currentText() #客票类型 self.price_value = self.price.text() #票价 if self.airline_value == '国内' and (self.jicang_value == '豪华头等舱' or self.jicang_value == '悦享经济舱' or self.jicang_value == '超级经济舱'): reply = QMessageBox.about(self.Widget, "提示", "国内航班无豪华头等舱、悦享经济舱、超级经济舱") elif self.price_value == '': reply = QMessageBox.about(self.Widget, "提示", "请填写机票价格") else: print(self.airline_value) Rule = rule.rule(self.total_bag, self.airline_value, self.start_value, self.jicang_value, self.kepiaotype_value, self.price_value) result = Rule.error_dealer() if result == 'free': reply = QMessageBox.about(self.Widget, "结果", "免费") elif result == 'error': reply = QMessageBox.about(self.Widget, "提示", "填写格式错误") elif result == 'ok': res, dw = Rule.count_dollar() if res == 0: reply = QMessageBox.about(self.Widget, "结果", "免费") elif res == -1: reply = QMessageBox.about(self.Widget, "结果", "不能托运") else: reply = QMessageBox.about(self.Widget, "结果", str(res) + dw) #print(self.airline_value,self.start_value,self.jicang_value,self.kepiaotype_value,self.huiyuan_value,self.price_value) print(self.total_bag)
import sys sys.path.append(r'..\CleanCode\CleanCode') import rule rule = rule.rule() rule.version(isShow=True) rule.analyse(r'.\case\rule0001.ini') input("按回车(Enter)继续")
for line in rule_file[1:]: if not line: continue try: rules.append(rule.rule(line.strip())) line_num += 1 except: raise BadFileError("Rule file is invalid (line %d) '%s'" % (line_num, line)) return rules, terminals if __name__ == "__main__": rules = [ rule.rule("S > NP VP"), rule.rule("NP > Art N"), rule.rule("VP > V"), ] lexemes = [ lexeme("a", ["Art"]), lexeme("the", ["Art"]), lexeme("child", ["N"]), lexeme("man", ["N"]), lexeme("laughs", ["V"]), lexeme("eats", ["V"]), ]
def setUp(self): self.r1 = rule(['a'], ['b'], 0.2, 0.8) self.r2 = rule(['a', 'b'], ['c'], 0.2, 0.8) self.r3 = rule(['a'], ['b', 'c'], 0.2, 0.8)
def setUp(self): self.ab = rule(['a'], ['b'], 0.2, 0.8) self.ac = rule(['a'], ['c'], 0.2, 0.8) self.bc = rule(['b'], ['c'], 0.2, 0.8) self.kb = KnowledgeBase([self.ab, self.ac, self.bc])
def adaboost(): # split the data to train and test train, test = train_test_split(ListPoint, test_size=0.5) # total of points n_samples = len(train) # init the weight to be 1/n array_weight = np.full(n_samples, (1 / n_samples)) # prediction array predictions = np.zeros(n_samples) # all possible straight equations from two points (rules) for i in range(0, n_samples): j = i + 1 for j in range(j, n_samples): # slope of equation slope_m = slope(train[i].x, train[i].y, train[j].x, train[j].y) # finding the midpoint midpoint = findMidpoint(train[i].x, train[i].y, train[j].x, train[j].y) if slope_m == 0: reverse_slope = 0 else: reverse_slope = (-1 / slope_m) # b of equation b_reverse = ((-1 * reverse_slope) * midpoint.x) + midpoint.y # idx_predict = 0 # error for this rule true_error = 0 alpha = 0 # check the rule on all the points for point in train: # check if the point is under the equation y = reverse_slope * point.x + b_reverse # check whether the point is above the line or below # if y > point.y -> the point is below the line if y > point.y: predictions[idx_predict] = 1 else: # the point is above the line predictions[idx_predict] = -1 # error on every point # print("---------> ", predictions[idx_predict] != point.label) mul = 1 if predictions[idx_predict] == point.label: mul = 0 # print("-----> ", array_weight[idx_predict]) error_point = np.multiply(array_weight[idx_predict], mul) # print("error Point: " ,error_point) # schema of all errors true_error = true_error + error_point idx_predict = idx_predict + 1 # If the true error > 0.5 we want the opposite rule print("True Error: ", true_error) if true_error > 0.5: label = 1 final_true_error = 1 - true_error # print("Final True Error: ", final_true_error, "True Error: ", true_error) else: label = -1 final_true_error = true_error # weight of the rule # print("Final True Error: ", final_true_error, "True Error: ", true_error) alpha = np.multiply(0.5, (np.log((1 - final_true_error + epsilon) / (final_true_error + epsilon)))) # insert to array of rules array_rules.append( rule(reverse_slope, b_reverse, alpha, label, final_true_error)) # The weight of all the points (for normalization) all_points_weight = 0 # changing the weights of the points according to the error for idx_weight in range(len(array_weight)): # calculates the new weight of the point -> e^(-alfa*h(x)*label(x)) num = (-1 * alpha) * (predictions[idx_weight] * train[idx_weight].label) e_exponent = np.exp(num) weight_point = array_weight[idx_weight] * e_exponent # update the new weight array_weight[idx_weight] = weight_point # sum the weights of all points # normalize the points NormalizationWeight(all_points_weight, array_weight) best_one_rules(train, 1) best_two_rules(train, 1) best_three_rules(train, 1) best_four_rules(train, 1) best_five_rules(train, 1) best_six_rules(train, 1) best_seven_rules(train, 1) best_eight_rules(train, 1) best_one_rules(test, 2) best_two_rules(test, 2) best_three_rules(test, 2) best_four_rules(test, 2) best_five_rules(test, 2) best_six_rules(test, 2) best_seven_rules(test, 2) best_eight_rules(test, 2)
async def on_message(msg): #botからのメッセージは無視 if msg.author.bot: return #ルールの出力 if msg.content == '.outrule': result = rule.rule() await msg.channel.send(embed=result[0]) await msg.channel.send(embed=result[1]) #メンバーの登録 if msg.content.startswith('.add'): result = excel.add_member(msg.content.split()) await msg.channel.send(result) #メンバーの除外 if msg.content.startswith('.remove'): result = excel.remove_member(msg.content.split()) await msg.channel.send(result) #メンバー一覧の表示 if msg.content.startswith('.allmember'): result = excel.all_member() embed = discord.Embed(title='登録されているメンバー一覧') embed.add_field(name='名前', value=result[0]) embed.add_field(name='ID', value=result[1]) embed.add_field(name='メンション', value=result[2]) await msg.channel.send(embed=embed) #凸予約 if msg.content.startswith('.set'): result = clanbattle.setin(msg.content.split(), msg.author.id) await msg.channel.send(result) await reload_status() #凸予約の取り消し if msg.content.startswith('.del'): result = clanbattle.delete(msg.content.split(), msg.author.id) await msg.channel.send(result) await reload_status() #持越しの登録 if msg.content.startswith('.co'): result = clanbattle.carry_over(msg.content.split(), msg.author.id) await msg.channel.send(result) await reload_status() #凸宣言,持越し宣言 if msg.content.startswith('.atk'): result = clanbattle.atk(msg.author.id) if result[1] == 0: await msg.add_reaction('✔️') if result[1] == 1: await msg.add_reaction('⭕') if result[1] == 2: await msg.add_reaction('❌') await msg.channel.send(result[0]) await reload_status() #凸の修正 if msg.content.startswith('.fix'): result = clanbattle.fix(msg.author.id) await msg.channel.send(result) await reload_status() #ボスの切り替え if msg.content == '.bc': result = clanbattle.boss_change() channel = client.get_channel(764803209066971156) await channel.send(result) await reload_status() #ボスの強制切り替え if msg.content.startswith('.bc set'): result = clanbattle.boss_set(int(msg.content.split()[2])) channel = client.get_channel(764803209066971156) await channel.send(result) await reload_status()
def GET(self): global access_token access_token = session.get('access_token',None) global expires_in expires_in = session.get('expires_in',None) #access_token = 0 if not access_token: client = APIClient(app_key=CONSUME_KEY, app_secret=CONSUME_SECRET, redirect_uri=web.ctx.get('homedomain')+'/callback') #auth = OAuthHandler(CONSUME_KEY, CONSUME_SECRET,web.ctx.get('homedomain')+'/callback') #获得新浪微博的认证url地址 auth_url = client.get_authorize_url() #auth_url = auth.get_authorization_url() logger.debug("认证地址为:%s"%auth_url) #在session中保存request_token,用于在新浪微博认证通过后换取access_token #session.request_token=auth.request_token print '1111111111111111111111111111111111111' print auth_url global errr errr = 4321 web.seeother(auth_url) else: #code = session.get('code') #return str(code) #client = APIClient(app_key=CONSUME_KEY, app_secret=CONSUME_SECRET, redirect_uri=web.ctx.get('homedomain')+'/callback') #auth_url = client.get_authorize_url() #auth = OAuthHandler(CONSUME_KEY, CONSUME_SECRET) #auth.access_token=access_token #r = client.request_access_token(code) #access_token = r.access_token #expires_in = r.expires_in #client.set_access_token(access_token, expires_in) #api=API(auth) #global weibo_api #weibo_api = api #user=api.verify_credentials() #client.get.account__get_uid() global client client = APIClient(app_key=CONSUME_KEY, app_secret=CONSUME_SECRET, redirect_uri=web.ctx.get('homedomain')+'/callback') #r = client.request_access_token(code) #access_token = r.access_token # 新浪返回的token,类似abc123xyz456 #return str(access_token ) #expires_in = r.expires_in # token过期的UNIX时间:http://zh.wikipedia.org/wiki/UNIX%E6%97%B6%E9%97%B4 # TODO: 在此可保存access token client.set_access_token(access_token, expires_in) self.client = client #user = client.get.account_get_uid() #return user #user = '' #id = client.get.account__get_uid() #friends=api.friends() total = 200 #sleep(1) #blogs = api.user_timeline(page=1,count = total,trim_user=1) blog = client.get.statuses__user_timeline(page=1,count = 1,trim_user=0).statuses user = blog[0]['user']['screen_name'] index = blog[0]['user']['statuses_count'] index = 300 #return user,index blogs = client.get.statuses__user_timeline(page=1,count = total,trim_user=1).statuses #index = user.statuses_count #return blogs #index = 2800 #web.header("Content-Type", "text/html;charset=utf-8") #return ':-( 出错了wqwqwsdsdsdqqqqqqqq' #获取全部 #print index mm = 21 try: #blogs += api.user_timeline(page=2,count = total,trim_user=1) blogs += client.get.statuses__user_timeline(page=2,count = total,trim_user=1).statuses except: print 'nook 2' mm = 11 for i in xrange(3,index/100 + 1): try: sleep(0.001) #blogs += api.user_timeline(page=i) blogs += client.get.statuses__user_timeline(page=i,count = total,trim_user=1).statuses except: print 'nook 3', i #break time_data = [] time_data_fzhuanf = [] time_data_zhuanf = [] test = "转发微" test2 = "//@" a = 0 for blog in blogs: #print blog.created_at.month #print blog.created_at.isocalendar() blog.created_at = time.strptime(str(blog.created_at),"%a %b %d %H:%M:%S +0800 %Y") if (blog.text[:3].encode('utf8') == test) or (blog.text[:3].encode('utf8') == test2): #print '11111111',blog.text[:3].encode('utf8') a+=1 time_data_zhuanf.append(blog.created_at) else: #print blog.text[:3].encode('utf8') time_data_fzhuanf.append(blog.created_at) time_data.append(blog.created_at) #print 'aaaaaaaaaaaaaaaa',a #return time_data,time_data_zhuanf,time_data_fzhuanf data_2012_M , data_2011_M, data_2012_W, data_2011_W,\ data_zhuanf,data_fzhuanf ,data_f_total,data_H\ = time_operate.time_operate(time_data,time_data_zhuanf,time_data_fzhuanf) #return render_template('index.html',friends=friends,user=user) #print blogs #pic1 = chart.plot_bar(name = 'The Number of weibo in 2012',value=data_2012_M['value'],label=month_label) #pic2 = chart.plot_bar(name = 'The Number of weibo in 2012',value=data_2011_M['value'],label=month_label) #aa = test_line() #print pic1 print time_data.__len__() web.header("Content-type","text/html") data_2012 =data_theme.op_year(data_2012_M['value']) data_2011 =data_theme.op_year(data_2011_M['value']) data_week_day = data_theme.op_week_day(data_2012_W,data_2011_W) data_zhuanf,data_fzhuanf,data_total = data_theme.op_zhuanf(data_zhuanf,data_fzhuanf,data_f_total) data_hour= data_theme.op_hour(data_H) #print '11111asasas',data_zhuanf,data_fzhuanf best_day,best_time = rule.rule(data_f_total,data_H) global best_date best_date = best_day global best_t best_t = best_time #return best_date,best_time #return data_2012_M , data_2011_M, data_2012_W, data_2011_W,data_zhuanf,data_fzhuanf ,data_f_total,data_H return render.index2(quantity = "%.0f" % (time_data.__len__()*100.0/(index)),picname = '2012',label=month_label,value1=data_2012,\ value2=data_2011,value3=data_week_day,\ zhuanf=data_zhuanf,fzhuanf=data_fzhuanf,\ combin=data_hour,f_total=data_total,\ best_day=best_day,best_time=best_time,blogs=blogs, user=user)
def adaboost(path, times, best_k): for t in range(times): print("Iteration: ", t) # read the data and create points in point_list read_file(path) # split the data to train and test train, test = train_test_split(point_list, test_size=0.5) # total of points n_samples = len(train) # init the weight to be 1/n array_weight = np.full(n_samples, (1 / n_samples)) # prediction array predictions = np.zeros(n_samples) true_error = 0 alpha = 0 index = 0 k = 0 for i in train: for j in train: true_error = 0 k = k + 1 alpha = 0 if i != j: # slope of equation slope_m = slope(i.x, i.y, j.x, j.y) # finding the midpoint midpoint = findMidpoint(i.x, i.y, j.x, j.y) if slope_m == 0: reverse_slope = 0 else: reverse_slope = (-1 / slope_m) # b of equation b_reverse = ( (-1 * reverse_slope) * midpoint.x) + midpoint.y # --------------- FIND THE ERROR FOR THIS RULE --------------- for p in train: # check if the point is under the equation y = reverse_slope * p.x + b_reverse # check whether the point is above the line or below # if y > point.y -> the point is below the line if y > p.y: predictions[index] = 1 else: # the point is above the line predictions[index] = -1 true_error = true_error + array_weight[index] * int( predictions[index] != p.label) if true_error < 0.5: alpha = 0.5 * np.log((1 - true_error + epsilon) / (true_error + epsilon)) rules_list.append( rule(reverse_slope, b_reverse, alpha, -1, true_error)) for w in range(len(array_weight)): array_weight[w] = array_weight[w] * np.exp( (-1 * alpha) * (predictions[w] * train[w].label)) sum_weight = np.sum(array_weight) NormalizationWeight(sum_weight, array_weight) rules_sort = sorted(rules_list, key=lambda rule: rule.alpha, reverse=True) for idx in range(best_k): # print("idx: ", idx) # print("k " , k) best_rules.append(rules_sort[idx]) check_success(1, train, "train") check_success(1, test, "test") check_success(2, train, "train") check_success(2, test, "test") check_success(3, train, "train") check_success(3, test, "test") print_rules()
def login(): errors = "" if request.method == "POST": name = None age = None email = None country = None state = None city = None password = None cough = None fever = None try: name = str(request.form["name"]) except: name = None try: age = int(request.form["age"]) except: age = None try: email = str(request.form["email"]) except: email = None try: country = str(request.form["country"]) except: country = None try: state = str(request.form["state"]) except: state = None try: city = str(request.form["city"]) except: city = None try: password = str(request.form["password"]) except: password = None try: cough = request.form["1"] except: cough = None try: fever = request.form["2"] except: fever = None try: tiredness = request.form["3"] except: tiredness = None try: medium_temperature = request.form["4"] except: medium_temperature = None try: low_temperature = request.form["5"] except: low_temperature = None try: difficulty_breathing = request.form["6"] except: difficulty_breathing = None try: shortness_of_breath = request.form["7"] except: shortness_of_breath = None try: aches_and_pains = request.form["8"] except: aches_and_pains = None try: sore_throat = request.form["9"] except: sore_throat = None try: diarrhoea = request.form["10"] except: diarrhoea = None try: nausea = request.form["11"] except: nausea = None try: runny_nose = request.form["12"] except: runny_nose = None try: Persistent_pain_or_pressure_in_the_chest = request.form["13"] except: Persistent_pain_or_pressure_in_the_chest = None try: Bluish_lips_or_face = request.form["14"] except: Bluish_lips_or_face = None try: a = request.form["15"] except: a = None try: b = request.form["16"] except: b = None try: c = request.form["17"] except: c = None try: d = request.form["18"] except: d = None try: flnm = request.form["19"] except: flnm = None try: result = int(request.form["result"]) except: result = 0 try: sea = request.form["search"] except: sea = None try: otp = int(request.form["otp"]) except: otp = None try: magik_string = request.form["magik_string"] except: magik_string = None if name is not None and age is not None and email is not None and country is not None and state is not None and city is not None and password is not None and result is not None: otp_sender(email, age) email = email.replace(' ', '_') name = name.replace(' ', '_') country = country.replace(' ', '_') state = state.replace(' ', '_') city = city.replace(' ', '_') password = password.replace(' ', '_') magik_string = '{name}:{age}:{email}:{country}:{state}:{city}:{password}:{result}'.format( name=name, age=age, email=email, country=country, state=state, city=city, password=password, result=result) return ''' <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> input { width: 100%; padding: 12px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; margin-top: 6px; margin-bottom: 16px; } input[type=submit] { background-color: #4CAF50; color: white; } .container { background-color: #f1f1f1; padding: 20px; } #message { display:none; background: #f1f1f1; color: #000; position: relative; padding: 20px; margin-top: 10px; } #message p { padding: 10px 35px; font-size: 18px; } </style>''' + ''' </head> <body> <h3>OTP VERIFICATION</h3> <div class="container"> <form action="." method="post"> <label for="usrname">OTP</label> <input type="text" id="usrname" name="otp" required> <input name="magik_string" type="hidden" value={magik}> <input type="submit" value="Submit"> </form> </div> </body> </html> '''.format(magik=magik_string) elif otp is not None and magik_string is not None: magik_list = magik_string.split(':') if len(magik_list) == 8: if int(otp) == int(int(magik_list[1]) * 2935): regf(str(magik_list[0].replace('_', ' ')), str(magik_list[2].replace('_', ' ')), magik_list[1], str(magik_list[3].replace('_', ' ')), str(magik_list[4].replace('_', ' ')), str(magik_list[5].replace('_', ' ')), str(magik_list[6].replace('_', ' ')), magik_list[7]) magik_string = None return ''' <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body { font-family: Arial, Helvetica, sans-serif; background-color: black; } * { box-sizing: border-box; } /* Add padding to containers */ .container { padding: 16px; background-color: white; } /* Full-width input fields */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1; } input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none; } /* Overwrite default styles of hr */ hr { border: 1px solid #f1f1f1; margin-bottom: 25px; } /* Set a style for the submit button */ .registerbtn { background-color: #4CAF50; color: white; padding: 16px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; opacity: 0.5; } .registerbtn:hover { opacity: 1; } /* Add a blue text color to links */ a { color: dodgerblue; } /* Set a grey background color and center the text of the "sign in" section */ .signin { background-color: #f1f1f1; text-align: center; } </style> </head> <body> <h2 STYLE="color:blue;text-align:center;opacity:20.9;">YOU ARE REGISTERED</h2> <form method="post" action="."> <div class="container"> <h1>Login</h1> <hr> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label for="Password"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="password" required> <hr> <button type="submit" class="registerbtn">Login</button> </div> <div class="container signin"> <p><a href="#">Forget Your Password</a></p> </div> </form> <form method="post" action="."> <div class="container"> <h1>Register</h1> <p>Please fill in this form to create an account.</p> <hr> <label for="name"><b>Name</b></label> <input type="text" placeholder="Enter Name" name="name" required> <label for="Age"><b>Age</b></label> <input type="text" placeholder="Enter Age" name="age" required> <label for="email"><b>Email</b></label> <input type="text" placeholder="Enter Email" name="email" required> <label for="country"><b>Country</b></label> <input type="text" placeholder="Enter Your Country" name="country" required> <label for="State"><b>State</b></label> <input type="text" placeholder="Enter Your State" name="state" required> <label for="city"><b>City</b></label> <input type="text" placeholder="Enter Your City" name="city" required> <label for="password"><b>Password</b></label> <input type="password" placeholder="Enter Your Password" name="password" required> <input type="hidden" name="result" value="0"> <hr> <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p> <button type="submit" class="registerbtn">Register</button> </div> </form> </body> </html> ''' else: return '''<!DOCTYPE html> <html> <body> <h2 style="text-align:center;">OTP IS INCORRECT</h2> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPEAAADRCAMAAAAquaQNAAABfVBMVEX+/v7+AADjy/3p2/71xuj7AAC9S4byAAD3AAC7UIi/SYW3WY6zYJShhq/4AAD0AAClfqqpdaO1XJK5VIyjgq2neaejhK6xZJj//P+od6bo3v/5ze7j0P+mfKj/+/urcaKfirHs5P/+8PDvh4f24O7sRUX88Pnxl5fxCBCejrWbgq/62dr97OzsVFPtHh/x1vDsanT2tbTsdoHxw9nAaonub4HiJTK1Pn7qFyfGSH30rq7ufn7+9fzsOTnsLy+uUInuwuntXVzvlbCTmb/zpKT4wsLKvNSzocLssbq8qsi1epzvZGqvhKjZzeD4ys7sU1v4ydnSRWbYOkrXIELRmbntj57AY5HwrsLHXnjLPGfXNFThJj7YqcXulaTxzubMSXTAcp76udLNhqyykrbucG/vobG6N3q3JG66a5LVOl7RVW/DYITEUoTjv9fHjrLthp7yrMrvoL7VNl7OU2nFYXrWRle8cY3d2OW2rcqPlbvbNULIx9ygpsW7nbPKOWqa665MAAARRElEQVR4nO2d6V/bRhrHY8JYMsY2YAMFzGGzFGFAHAnGJAUMuVqgoUAhHG2A5tiQsCUJpUe6zd++88xItmyPbEkzOvJZ/97spi8sfXlmnt8zozlu3Wqqqaaa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rh1gOd98+///BluWD1VNBJuC0i6kUqZ9aQco1xCa/3oTWqaoXyXrhNlDeNGv+Y0vUGpv3rrwd+hdagh3IlsahPT4asJd38PoFx//u3n6E16J4xvxyH28R4UylrJXAZ+eBBYGiJjFNBH8NnQn5Ty1q4jBzBsIHbDGtwkY+Cri6DrBVXr//xv9eyVZ4KOhIzbzsaQtLsD4ELrUGlFcpHSRExuadsPhoS8DtuaohOBaHPIrwpO5cV8Cuui6xQRp8DsAXKM8FnKbQU5L4nXONyKH7g90t4q4cJ+f+pUYPmFL/fwHNN+v0CTTXVVFNNNdVUU01V6n9BYJCiZyLYUAAAAABJRU5ErkJggg==" alt="Trulli" width="100%" height="333"> </body> </html> ''' else: return '''len of mk lt is {x} {y} '''.format(x=len(magik_list), y=magik_list[0]) elif email is not None and password is not None: with open('data.txt', 'r') as f: for l in f: l = l.split(':') if email == l[0] and password == l[1]: data_base = l name = data_base[2] age = data_base[3] email = data_base[0] location = data_base[4] + ' ' + data_base[ 5] + ' ' + data_base[6] password = data_base[1] try: with open('status.txt', 'r') as ff: for ll in ff: ll = ll.split(':') if ll[0] == str(email) + str(password): status = int(ll[1]) except: status = 0 rules = rule(status) rules = rules.split(':') try: rule0 = rules[0] except: rule0 = None try: rule1 = rules[1] except: rule1 = None try: rule2 = rules[2] except: rule2 = None try: rule3 = rules[3] except: rule3 = None try: rule4 = rules[4] except: rule4 = None try: rule5 = rules[5] except: rule5 = None try: rule6 = rules[6] except: rule6 = None try: rule7 = rules[7] except: rule7 = None return '''<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <style> * {box-sizing: border-box;} } .topnav { overflow: hidden; background-color: #e9e9e9; } .topnav a { float: left; display: block; color: black; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } .topnav a:hover { background-color: #ddd; color: black; } .topnav a.active { background-color: #2196F3; color: white; } .topnav .search-container { float: right; } .topnav input[type=text] { padding: 6px; margin-top: 8px; font-size: 17px; border: none; } .topnav .search-container button { float: right; padding: 6px 10px; margin-top: 4px; margin-right: 12px; background: #ddd; font-size: 17px; border: none; cursor: pointer; width:10px; } .topnav .search-container button:hover { background: #ccc; } @media screen and (max-width: 500px) { .topnav .search-container { float: none; } .topnav a, .topnav input[type=text], .topnav .search-container button { float: none; text-align: left; width: 90%; margin: 0; padding: 14px; } .topnav input[type=text] { border: 1px solid #ccc; } } .card { box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); max-width: 100%; margin: auto; text-align: center; font-family: Georgia; background-image:url('https://cdn.pixabay.com/photo/2016/09/13/19/31/texture-1668079_960_720.jpg'); width:100%; height:100%; } .title { color: grey; font-size: 18px; } button { border: none; outline: 0; display: inline-block; padding: 8px; color: white; background-color: #000; text-align: center; cursor: pointer; width: 100%; font-size: 50px; } .buttonn { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 16px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 20px; margin: 4px 2px; transition-duration: 0.4s; cursor: pointer; } .button2 { background-color: #008CBA; color: black; border: 2px solid #008CBA; opacity: 0.7; } .button2:hover { background-color: #008CBA; color: white; } .but{ width:32px; height:33px; margin-top:7px; } .ccc{ width:85%; } a { text-decoration: none; font-size: 22px; color: white; } button:hover, a:hover { opacity: 0.7; } </style> ''' + ''' </head> <body> <form action="." method="post"> <input type="text" placeholder="Search.." name="search" class="ccc"> <button type="submit" class="but"><i class="fa fa-search"></i></button> </form> <h2 style="text-align:center">CORONA STATUS</h2> <div class="card"> <img src="https://images.pexels.com/photos/3952232/pexels-photo-3952232.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="John" style="width:100%;height:500px;"> <h1>{name}</h1> <p class="title">Age {age}</p> <p> {location}</p> <p>Corona Status </p><meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <div class="w3-light-grey"> <div class="w3-container w3-blue" style="width:{perct}%">Status </div> </div><br> <p>Score {perc}</p> <p><button>Contact {email}</button></p> </div> <form action="http://staysafe008.pythonanywhere.com/" method="post"><input name=userpass value="{email}:{password}" type="hidden"><button class="buttonn button2" type="submit">UPDATE STATUS</button></form> <form action="." method="post" ><input type="hidden" name="email" value={email}> <input type="hidden" name="password" value={password}> <button type="submit">Reload</button></form> <div class="card"> <p >Score 0-2 Best</p> <p >Score 3-5 Good</p> <p >Score 6-10 Follow the rules</p> <p >Score 11-30 Danger</p> <p >{rule1}</p><br> <p >{rule2}</p><br> <p >{rule3}</p><br> <p >{rule4}</p><br> <p >{rule5}</p><br> <p >{rule6}</p><br> <p >{rule7}</p><br> <p >{rule8}</p><br> <p><button></button></p> <script src='https://kit.fontawesome.com/a076d05399.js'></script> <form action="#"> <button type="submit" style='font-size:24px;width:100%;'>Donate <i class='fas fa-dollar-sign'></i></button> </form> </div> </body> </html>'''.format(name=name, age=age, location=location, status=status, email=email, password=password, perc=status, rule1=rule0, rule2=rule1, rule3=rule2, rule4=rule3, rule5=rule4, rule6=rule5, rule7=rule6, rule8=rule7, perct=(status * 100) / 30) elif flnm is not None: list_of_symps = [ cough, fever, tiredness, medium_temperature, low_temperature, difficulty_breathing, shortness_of_breath, aches_and_pains, sore_throat, diarrhoea, nausea, runny_nose, Persistent_pain_or_pressure_in_the_chest, Bluish_lips_or_face, a, b, c, d ] list_of_symps_org = [ 'cough', 'fever', 'tiredness', 'medium temperature(95.9–99.5 °F)', 'low temperature(<95 °F)', 'difficulty breathing', 'shortness_of_breath', 'aches and pains', 'sore throat', 'diarrhoea', 'nausea', 'runny_nose', 'Persistent pain or pressure in the chest', 'Bluish lips or face', 'I have traveled recently during the last 14 days', 'I have a travel history in COVID-19 infected area', 'I have direct contact or is taking care of a positive COVID-19 patient', 'Sneezing frequency(High)' ] tempstring = '' for i in range(len(list_of_symps)): if list_of_symps[i] is not None: tempstring += str(list_of_symps_org[i]) + ':' else: continue tempstring = tempstring.split(':') result = corona_checker_bot(tempstring) with open("status.txt", "r") as gile: user_data = gile.readlines() for i in range(len(user_data)): if user_data[i].split(':')[0] == str(flnm).replace( ':', ''): user_data[i] = str(flnm).replace( ':', '') + ':' + str(result) + '\n' with open("status.txt", "w") as writeg: for line in user_data: writeg.write(line) flnm = flnm.split(':') email = flnm[0] password = flnm[1] return '''<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body, html { height: 100%; font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } .bg-img { /* The image used */ background-image: url("https://images.unsplash.com/photo-1558591710-4b4a1ae0f04d?ixlib=rb-1.2.1&w=1000&q=80"); height: 100%; width:100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; position: relative; } /* Add styles to the form container */ .container { position:absolute; right: 0; margin-top:50px; width: 100%; padding: 16px; height:220px; background-color: white; } /* Full-width input fields */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 5px 0 22px 0; border: none; background: #f1f1f1; } input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none; } /* Set a style for the submit button */ .btn { background-color: red; color: white; padding: 16px 20px; border: none; cursor: pointer; width: 100%; opacity: 0.8; } .btn:hover { opacity: 1; } </style>''' + ''' </head> <body> <div class="bg-img"> <form action="." method="post"class="container"> <h1 style="text-align:center;color:dark;">YOUR STATUS HAS BEEN UPDATED</h1> <input type="hidden" name="email" value={email}> <input type="hidden" name="password" value={password}> <button type="submit" class="btn">home</button> </form> </div> </body> </html> '''.format(email=email, password=password) elif sea is not None: magik_string = search(sea) if magik_string: return magik_string else: return '''<!DOCTYPE html> <html> <body> <figure> <img src="https://cdn.dribbble.com/users/283708/screenshots/7084440/media/6cd8b29540bcfb6a7693c27f58db7b56.png" alt="Trulli" style="width:100%"> <figcaption><b style="text-align:center;">OUR SEARCH RESULTS ARE CASE SENSITIVE.</b></figcaption> </figure> </body> </html> ''' errors += "Login Failed" return '''<!DOCTYPE html>
def init(): logging.debug("Rules init") for r in configuration.rules: rules[r["name"]] = rule.rule(r["name"], r["rule"], r["inputs"], r["outputs"])
''' this tool will get your clipboard. if there is any we can do, we will do it. ''' from rule import rule #from tools import detect_change import pyperclip as clip from time import sleep # global var defined detent_time = 2 # some seconds FLAG = 1 # loop FLAG old_str = "" # main loop while(FLAG): sleep(detent_time) a = clip.paste() if a==old_str: continue print('get new paster board value: ' + a + '\n') a = rule(a) print('revised: ' + a + '\n') clip.copy(a) old_str = a
def test_compare(self,baggage,airline_area,start,cabin_type,Ticket_type,price, expect): r=rule(baggage,airline_area,start,cabin_type,Ticket_type,price) actual =r.count_dollar()[0] self.assertEqual(actual, expect)