def rule(): print("Going to Rules...\n\n") os.system('cls') rules.rules() file=open("rnav.txt", "r") option=file.read() if option=="1": os.system('cls') play() elif option=="2": os.system('cls') main()
def calculate_information_gain_star(dataset, classification_file, rule_set, rule_number): if 'users' in dataset: df_dataset = pandas.read_csv(dataset) attribute = rules.attributes(rule_set,rule_number) if isinstance(attribute,list): attribute_list = [] attrs = df_dataset[attribute].values for attr in attrs: rule_output = rules.rules(rule_set, rule_number, attr) if rule_output == 1: number_satisfied = 1 else: number_satisfied = 0 attribute_list.append(number_satisfied) else: attribute_list = df_dataset[attribute].values df_classification = pandas.read_csv(classification_file) classification_list = df_classification['class'].values print(classification_list) print(attribute_list) information_gain_star = info_gain.info_gain(classification_list, attribute_list) else: attribute = rules.attributes(rule_set, rule_number) df_dataset = pandas.read_csv(dataset) user_id_list = list(set(df_dataset['user_id'].values)) df_classification = pandas.read_csv(classification_file) attr_values = [] real_classes = [] for user_id in user_id_list: df_user = df_dataset.loc[df_dataset['user_id'] == user_id] attribute_list = df_user[attribute].values attribute_value = attribute_list[0] number_satisfied = 0 if rule_number == 22: number_satisfied = len(df_user[attribute].unique()) elif rule_number == 3 and rule_set == 'social_bakers': number_satisfied = df_user[attribute].value_counts().max() else: for attr in attribute_list: rule_output = rules.rules(rule_set, rule_number, attr) if rule_output == 1: number_satisfied += 1 attr_values.append(number_satisfied) df_class = df_classification.loc[df_classification['id'] == user_id] real_class = df_class['class'].values[0] real_classes.append(real_class) information_gain_star = info_gain.info_gain(real_classes, attr_values) return information_gain_star
def getPolicyMoveList(self): moveFound, _type = rules(self.current_player, self.board, self.NS).policy_type_search_move() if moveFound != None: return moveFound, _type else: return self.get_empty_points(), _type
def sample(self): print('generating samples') for _trace in tqdm(self.get_test_set(), ascii=True): for _index, _abr in enumerate(self.abr_list): self.sample_list[_index].append( sabre.execute_model(abr=_abr, trace=_trace)) for _index0 in range(len(self.abr_list)): _battle = [] for _index in range(len(self.abr_list)): tmp = [0, 0, 0] for _trace_index in range(len(self.get_test_set())): res = rules([ self.sample_list[_index0][_trace_index], self.sample_list[_index][_trace_index] ]) if _index0 < _index: self.elo_score = update_elo(self.elo_score, _index0, _index, res) tmp[np.argmax(res)] += 1 tmp[-1] += 1 _battle.append(round(tmp[0] * 100.0 / tmp[-1], 2)) print(_index0, _battle) log_file = open('elo_baseline.txt', 'w') for p in self.elo_score: log_file.write(str(p) + ' ') log_file.close() print(self.elo_score)
def get_relation(self, ner_result): history = {} history["relations"] = [] history["rel_tags"] = [[]] history["tags"] = ner_result["tags"] history["wn"] = 0 wmap = [] wmap.append({"words": ner_result["words"]}) supported_rel = [ "price_query", "feature_query", "interest_intent", "comparison", "irrelevant" ] #,"disagreement","agreement","greeting","acknowledgement"] func_obj = rer_feature_functions.RerFeatureFunctions( ) #, supported_tags) func_obj.set_wmap(wmap) clf = rermymaxent([], func_obj, supported_rel, reg_lambda=0.001, pic_file="rer_all_data.p") r = rules() val1 = clf.classify(history) val2 = r.classify(ner_result["words"]) if val2 != None: val = val2 else: val = val1 result = {} result["words"] = wmap[0]["words"] result["tag"] = history["tags"] result["relation"] = val return result
def setup_rules(self, allowed_rule_names): allowed_rule_names = set(rule_name.lower() for rule_name in allowed_rule_names) self.rules = [] for r in rules.rules(self.space, self.deduction_types): if not allowed_rule_names or r.name.lower() in allowed_rule_names: self.add_rule(r)
def menuloop(): # цикл обработки меню while True: mode = menu() clear() if mode == "1": # описание description() clear() elif mode == "2": # правила игры rules() clear() elif mode == "3": # играть playgame() clear() elif mode == "4": # выход из программы break else: wrong()
def central(net_params_queues, exp_queues): global_agent_list = [] agent_elo = [] _log = log('zero.txt') #log_file = open('zero.txt', 'w') elo_file = open('elo.txt', 'w') for p in range(NUM_AGENT): global_agent_list.append(Zero(str(p))) agent_elo.append(1000.0) _tracepool = tracepool(ratio=0.5) _split_pool, _idx_pool = chunks(_tracepool.get_list(), USE_CORES) while True: # synchronize the network parameters of work agent _params = [] agent_elo = [] global_trace_pool = [] for p in range(len(_tracepool.get_list())): global_trace_pool.append([]) for p in range(NUM_AGENT): agent_elo.append(1000.0) _params.append(global_agent_list[p].get_params()) for i in range(USE_CORES): net_params_queues[i].put([_params, _split_pool[i]]) _tmp = [0, 0, 0] for i in range(USE_CORES): _global_history, _trace_result = exp_queues[i].get() for p in range(NUM_AGENT): _history = _global_history[p] global_agent_list[p].set_action(_history) for p in range(len(_trace_result)): global_trace_pool[_idx_pool[i][p]] = _trace_result[p] for _trace_res in global_trace_pool: tmp_battle = rules(_trace_res) _log.write_log(_trace_res) _tmp[np.argmax(tmp_battle)] += 1 _tmp[-1] += 1 _rate, agent_elo = _tracepool.battle(agent_elo, global_trace_pool) _delta_array = [_tmp[0] / _tmp[-1], _tmp[1] / _tmp[-1]] for _agent, _d in zip(global_agent_list, _delta_array): _agent.learn(_d) _agent.clear() for p in agent_elo: elo_file.write(str(p) + ' ') elo_file.write('\n') elo_file.flush() print(_rate) print(agent_elo) print(round(_tmp[0] * 100.0 / _tmp[-1], 2), '%', ',', round(_tmp[1] * 100.0 / _tmp[-1], 2), '%') _log.write_line() os.system('python draw.py')
def open_sub_section(self): if self.position_fire==245: self.root.destroy() jeu.jeu(self.email) elif self.position_fire==310: self.root.destroy() import rules as ru ru.rules(self.email) elif self.position_fire==375: self.root.destroy() import score as sc sc.score(self.email) elif self.position_fire==440: self.root.destroy() import credit as cd cd.credit(self.email) elif self.position_fire==505: self.root.destroy()
def check_rule(rule_set, number, row): attribute = rules.attributes(rule_set, number) if isinstance(attribute, list): attribute_value = [] for attr in attribute: attribute_value.append(row[attr]) else: attribute_value = row[attribute] rule_output = rules.rules(rule_set, number, attribute_value) return rule_output
def check_rule(rule_set, number, rules_dict, row): attribute = rules.attributes(rule_set, number) if isinstance(attribute, list): attribute_value = [] for attr in attribute: attribute_value.append(row[attr]) else: attribute_value = row[attribute] rule_output = rules.rules(rule_set, number, attribute_value) if rule_output == 1: rule_index = 'rule_' + str(number) rules_dict[rule_index] = True return rules_dict
def employRules(self,ruleList): #ruleList is name of rules (e.g. "Shield", "Halberd", "Innate Defence (5+)" etc #import rules ruleDict = rules() ruleDict.makefullDict() for rule in ruleList: try: exec(ruleDict.fullDict[rule]) #ok self.rules.append(rule) except KeyError: print('\n%s is not found in Dictionaries!\n'%rule) import time time.sleep(2)
def _battle_index(self, agent_elo, agent_result, index): ret = [] for _index in range(len(self.abr_list)): tmp = [0, 0, 0] for _trace_index in range(len(self.get_test_set())): res = rules([ agent_result[_trace_index][index], self.sample_list[_index][_trace_index] ]) agent_elo = update_elo_2(agent_elo, self.elo_score, index, _index, res) # if res[0] != 0: tmp[np.argmax(res)] += 1 tmp[-1] += 1 ret.append(round(tmp[0] * 100.0 / tmp[-1], 2)) return ret, agent_elo
def compute(): json_file = r"rer_all_data.json" pickle_file = r"rer_all_data.p" # ---------------------------------------------------------------- TRAIN = 1 #int(raw_input("Enter 1 for Train, 0 to use pickeled file: ")) supported_tags = [ "Org", "OS", "Version", "Family", "Price", "Phone", "Feature", "Other" ] supported_rel = [ "price_query", "feature_query", "interest_intent", "comparison", "irrelevant" ] #,"disagreement","agreement","greeting","acknowledgement"] tag_set = {"Org": 0, "Other": 1} dims = 9 trg_data_x = [] trg_data_y = [] trg_data = {'Org': [], 'Other': []} data = json.loads(open(json_file).read())['root'] (rer_history_list, wmap) = rer_feature_functions.build_history(data[0:75], supported_tags) print "After build_history" func_obj = rer_feature_functions.RerFeatureFunctions() #, supported_tags) func_obj.set_wmap(wmap) clf = rermymaxent(rer_history_list[1:1400], func_obj, supported_rel, reg_lambda=0.001, pic_file=pickle_file) #print clf.model if TRAIN == 1: clf.train() r = rules() results = rer_feature_functions.test(clf, r, rer_history_list[1:200], wmap) expected = [] predicted = [] for result in results: expected.append(result['expected']) predicted.append(result['predicted']) met_obj = rer_metrics.rer_metrics(expected, predicted) metrics = met_obj.compute() print metrics
def agent(agent_id, net_params_queue, exp_queue): agent_list = [] for p in range(NUM_AGENT): agent_list.append(Zero(str(p))) while True: net_params, _tracepool = net_params_queue.get() for i in range(NUM_AGENT): agent_list[i].set_params(net_params[i]) _trace_result = [] _global_history = [] for p in range(NUM_AGENT): _global_history.append([]) for _trace in _tracepool: agent_result = [] for _agent in agent_list: total_bitrate, total_rebuffer, total_smoothness = env.execute( abr=_agent, trace=_trace) agent_result.append( (total_bitrate, total_rebuffer, total_smoothness)) agent_reward = [] for _index in range(len(agent_list[0].quality_history)): res = rules([ agent_list[0].quality_history[_index], agent_list[1].quality_history[_index] ]) agent_reward.append(res) agent_reward = np.array(agent_reward) for _index, _agent in enumerate(agent_list): _history = _agent.get_action() reward = agent_reward[:, _index] _idx = 0 s_batch, a_batch, r_batch, g_batch = [], [], [], [] for (state, action, gan) in _history: s_batch.append(state) a_batch.append(action) r_batch.append(reward[_idx]) g_batch.append(gan) _idx += 1 _global_history[_index].append( (s_batch, a_batch, r_batch, g_batch)) _trace_result.append(agent_result) exp_queue.put([_global_history, _trace_result])
def check_vdb_rule(rule_set, number, row, df_row): rule_satisfied = 0 attribute = rules.attributes(rule_set, number) if number == 4: attribute_value = [] attribute_value.append(row[attribute]) attribute_value.append(df_row[attribute]) elif number == 3: attribute_value = df_row else: if isinstance(attribute, list): attribute_value = [] for attr in attribute: attribute_value.append(row[attr]) else: attribute_value = row[attribute] rule_output = rules.rules(rule_set, number, attribute_value) return rule_output
def solve(text): """ Answers a word problem. Paramater --------- text: str Question with multiple sentences. See examples in data.py Returns ------- Currently not specified """ rules = ru.rules() _,_,tags = preprocess(text) # Debug for tag in tags: print tag print '------------' # Extract grammar regexp portion from grammar rules grammar = [rule[0] for rule in rules] for tag in tags: index = -1 for g in grammar: matches = compare(tag, g) index += 1 # If a match is found, exit if matches[0] is not 'None': break # If match is not found, ignore sentence if matches[0] is 'None': continue results = check_match(matches, rules[index]) apply_results(results) print environment
def sample(self): print('generating samples') for _trace in self.get_test_set(): for _index, _abr in enumerate(self.abr_list): _f = open('./norway/log_sim_' + _abr + '_' + _trace, 'r') _bitrate, _rebuffer = [], [] for lines in _f: #110.64486915972032 2850 19.235901151929067 0.0 1341201 5257.885326692943 0.5 2.85 sp = lines.split() if (len(sp) > 0): _bitrate.append(float(sp[1])) _rebuffer.append(float(sp[3])) _bitrate_mean = np.mean(_bitrate[1:]) _rebuffer_mean = np.mean(_rebuffer[1:]) self.sample_list[_index].append( [_bitrate_mean, _rebuffer_mean]) for _index0 in range(len(self.abr_list)): _battle = [] for _index in range(len(self.abr_list)): tmp = [0, 0, 0] for _trace_index in range(len(self.get_test_set())): res = rules([ self.sample_list[_index0][_trace_index], self.sample_list[_index][_trace_index] ]) if _index0 < _index: self.elo_score = update_elo(self.elo_score, _index0, _index, res) tmp[np.argmax(res)] += 1 tmp[-1] += 1 _battle.append(round(tmp[0] * 100.0 / tmp[-1], 2)) print(_index0, _battle) log_file = open('elo_baseline.txt', 'w') for p in self.elo_score: log_file.write(str(p) + ' ') log_file.close() print(self.elo_score)
def setup_rules(self): self.rules = [] for r in rules.rules(self.space, self.deduction_types): self.add_rule(r)
def fetch(projectId): db = TinyDB("project_dbs/" + projectId + ".json") from rules import rules from display_results import display_results from insert_entity import insert_entity from categories.firewalls import add_affected_instances, add_network_rules from categories.roles import insert_roles import categories.compute_engine from categories.service_account_keys import insert_service_account_keys import categories.service_accounts import categories.service_account_IAM_policy import categories.buckets try: insert_entity(projectId, "compute", ["networks"], "Network") except Exception as e: print("Failed to fetch networks.") logging.exception("networks") try: insert_entity(projectId, "compute", ["firewalls"], "Firewall") except Exception as e: print("Failed to fetch firewalls.") logging.exception("firewalls") try: insert_roles(projectId, db) except Exception as e: print("Failed to fetch roles.") logging.exception("roles") try: categories.service_accounts.insert_service_accounts(projectId, db) categories.service_accounts.insert_sa_roles(projectId, db) except Exception as e: print("Failed to fetch service accounts.") logging.exception("service accounts") try: insert_service_account_keys(projectId, db) except Exception as e: print("Failed to fetch service account keys.") logging.exception("service account keys") try: categories.service_account_IAM_policy.insert_sa_policies(projectId, db) except Exception as e: print("Failed to fetch service account IAM policies.") logging.exception("service account IAM policies") try: insert_entity(projectId, "storage", ["buckets"], "Bucket") except Exception as e: print("Failed to fetch buckets.") logging.exception("buckets") try: categories.buckets.insert_acls(db) categories.buckets.insert_defacls(db) except Exception as e: print("Failed to fetch bucket ACLS/DEFACLS.") logging.exception("bucket acls/defacls") try: categories.compute_engine.insert_instances(projectId, db) insert_entity(projectId, "compute", ["instanceTemplates"], "Instance Template") categories.compute_engine.insert_instance_groups(projectId, db) categories.compute_engine.add_member_instances(projectId, db) except Exception as e: print("Failed to fetch compute engine instances.") logging.exception("compute engine instances") try: add_network_rules(projectId, db) add_affected_instances(projectId, db) except Exception as e: print("Failed to display instances/rules with instances.") logging.exception("add network rules/instances") try: insert_entity(projectId, "compute", ["snapshots"], "Snapshot") except Exception as e: print("Failed to fetch instance snapshots.") logging.exception("snapshots") try: insert_entity(projectId, "sqladmin", ["instances"], "SQL Instance", "v1beta4") except Exception as e: print("Failed to fetch SQL instances.") logging.exception("SQL instances") try: insert_entity(projectId, "pubsub", ["projects", "topics"], "Topics", "v1", "projects/", "topics") insert_entity(projectId, "pubsub", ["projects", "subscriptions"], "Pub/Sub", "v1", "projects/", "subscriptions") except Exception as e: print("Failed to fetch Pub/Sub topics/subscriptions.") logging.exception("pub/sub") try: rules(projectId) except Exception as e: logging.exception(e) display_results(db, projectId)
import time from db_helper import db_helper from rules import rules from weather_forecast import weather_forecast weather_forecast = weather_forecast() db_helper = db_helper() rules = rules() while True: av_moisture_L12H = 9999 # Get data try: weather_forecast.get_forecast() # check data forecast_current = weather_forecast.check_forecast_current() # Extract precipitation info min_precip = weather_forecast.get_min_precip() prob_precip = weather_forecast.get_prob_precip() min_precip_0 = min_precip[0] min_precip_1 = min_precip[1] prob_precip_0 = prob_precip[0] prob_precip_1 = prob_precip[1] except Exception as ex1: print(str(ex1))
def __init__(self): self.rule = rules() self.rule_list = self.rule.read_rules() self.rule_replace = self.rule.read_replace_rules()
def analyzeAV(arch,av,os,web,dir): # rav[] store CWSS values from rules rav=[] for comp in av: #attributesbyrules rav.append(rules.rules(comp)) #loadAttCWE has new features CWE=static.loadAttCWE() # sav[] store individual attribute scores from rav[] sav=[] #create the minidom document doc = Document() #create the <root> base element root = doc.createElement("Attack_Vector") doc.appendChild(root) for j in range(0,len(av)): "" sav.append(rav[j]) #Scores for non top25 weaknesses s = [sav[j][0],sav[j][1],sav[j][2],sav[j][3],sav[j][4],sav[j][5],sav[j][6],sav[j][7],sav[j][8],sav[j][9],sav[j][10],\ sav[j][11],sav[j][12],sav[j][13],sav[j][14],sav[j][15],sav[j][16],sav[j][17],sav[j][18]] #Scores for top25 weaknesses s25 = [sav[j][19],sav[j][20],sav[j][21],sav[j][22],sav[j][23],sav[j][24],sav[j][25],sav[j][26],sav[j][27],sav[j][28],\ sav[j][29],sav[j][30],sav[j][31],sav[j][32],sav[j][33],sav[j][34],sav[j][35],sav[j][36],sav[j][37]] # s = ["%.2f"%elem for elem in s] s25 = ["%.2f"%elem for elem in s25] # match={} ntchos={} match,ntchos=subAV(av[j].cLang,s,s25,CWE) # component = doc.createElement("Component") component.setAttribute("name",av[j].cName) for k in match.keys(): elemcwe = doc.createElement("CWE") id="CWE-"+k #We select weaknesses related to the operating system involved ("Unix Linux Mac"), so far! if (os=="ULM" and (k not in listOS)): #We select weaknesses NOT related to web applications or services here if ((not web) and (k not in listWEB)): elemcwe.setAttribute("id",id) name=ntchos[k][0] elemcwe.setAttribute("name",name) elemcwe.setAttribute("top25",ntchos[k][1]) elemcwe.setAttribute("childof",ntchos[k][2]) elemcwe.setAttribute("os",ntchos[k][3]) component.appendChild(elemcwe) "" attrib = doc.createElement("Attribute") for l in range(0,len(match[k])): if ((l%2)==0): safeatt=match[k][l] else: valueatt=match[k][l] attrib.setAttribute(safeatt,valueatt) elemcwe.appendChild(attrib) component.appendChild(elemcwe) root.appendChild(component) avfile="workspace/"+dir+"/xml/"+arch+".xml" file = open(avfile,"wb") try: file.write(doc.toprettyxml(indent=" ")) finally: file.close() return 0
def fetch(projectId): db = TinyDB("project_dbs/" + object_id_to_directory_name(projectId) + ".json") from rules import rules from display_results import display_results from insert_entity import insert_entity, insert_subnet_entities from categories.firewalls import add_affected_instances, add_network_rules from categories.roles import insert_roles import categories.compute_engine from categories.service_account_keys import insert_service_account_keys import categories.service_accounts import categories.service_account_IAM_policy import categories.buckets from categories.addresses import insert_addresses # initialize the entity database tables for the project, so that running G-Scout more than once against the same project doesn't result in duplicated data # I did this as an explicit list of tables so that if future versions store data that should persist between runs, those aren't deleted. entity_table_names = ["Address", "Bucket", "Cluster", "Compute Engine", "Finding", "Firewall", "Instance Template", "Network", "Pub/Sub", "Role", "Rule", "Service Account", "Snapshot", "SQL Instance", "Subnet", "Topics"] for tn in entity_table_names: db.purge_table(tn) try: insert_entity(projectId, "compute", ["networks"], "Network") except Exception as e: print("Failed to fetch networks.") logging.exception("networks") try: insert_subnet_entities(projectId) except Exception as e: print("Failed to fetch subnets: %s" % (e)) logging.exception("subnets: %s" % (e)) try: insert_entity(projectId, "compute", ["firewalls"], "Firewall") except Exception as e: print("Failed to fetch firewalls.") logging.exception("firewalls") try: insert_roles(projectId, db) except Exception as e: print("Failed to fetch roles.") logging.exception("roles") try: insert_entity(projectId, "iam", ["projects","serviceAccounts"], "Service Account", "v1", "projects/", "accounts") categories.service_accounts.insert_sa_roles(projectId, db) except Exception as e: print("Failed to fetch service accounts.") logging.exception("service accounts") try: insert_service_account_keys(projectId, db) except Exception as e: print("Failed to fetch service account keys.") logging.exception("service account keys") try: categories.service_account_IAM_policy.insert_sa_policies(projectId, db) except Exception as e: print("Failed to fetch service account IAM policies.") logging.exception("service account IAM policies") try: insert_entity(projectId, "storage", ["buckets"], "Bucket") except Exception as e: print("Failed to fetch buckets.") logging.exception("buckets") try: categories.buckets.insert_acls(db) categories.buckets.insert_defacls(db) except Exception as e: print("Failed to fetch bucket ACLS/Default ACLS: %s" % (e)) logging.exception("bucket ACLS/Default ACLS: %s" % (e)) try: categories.compute_engine.insert_instances(projectId, db) insert_entity(projectId, "compute", ["instanceTemplates"], "Instance Template") categories.compute_engine.insert_instance_groups(projectId, db) except Exception as e: print("Failed to fetch compute engine instances.") logging.exception("compute engine instances") try: categories.compute_engine.add_member_instances(projectId, db) except Exception as e: print("Failed add member instances to compute engine instances.") logging.exception("compute engine instances") try: add_network_rules(projectId, db) add_affected_instances(projectId, db) except Exception as e: print("Failed to display instances/rules with instances.") try: insert_addresses(projectId, db) except Exception as e: print("Failed to fetch IP addresses") print(e) try: insert_entity(projectId, "compute", ["snapshots"], "Snapshot") except Exception as e: print("Failed to fetch instance snapshots.") logging.exception("snapshots") try: insert_entity(projectId, "sqladmin", ["instances"], "SQL Instance", "v1beta4") except Exception as e: print("Failed to fetch SQL instances.") logging.exception("SQL instances") try: insert_entity(projectId, "pubsub", ["projects", "topics"], "Topics", "v1", "projects/", "topics") insert_entity(projectId, "pubsub", ["projects", "subscriptions"], "Pub/Sub", "v1", "projects/", "subscriptions") except Exception as e: print("Failed to fetch Pub/Sub topics/subscriptions.") logging.exception("pub/sub") try: insert_entity(projectId, "container", ['projects','locations','clusters'],"Cluster","v1beta1","projects/","clusters","/locations/-") except: print("Failed to fetch clusters") logging.exception("GKE") try: rules(projectId) except Exception as e: logging.exception(e) display_results(db, projectId)
#SetBehaviorClient(behav_,"robot_0") def now_time(start): return time.time() - start attack_hold_value = 31 attack_hold_degre = 10 # 초당 value 10씩 감소, 최대 3번, 한 자리에서 계속 공격하지 않게 하는 값. value가 occupy_hold_value = 200 if __name__ == '__main__': team1 = 'blue' team2 = 'red' robot1 = rules.rules([200, 320], team1) robot3 = rules.rules([200, 320], team2) ''' ================================================== Get Value from Black Board ================================================== ''' initialize() #stance = 'passive' stance = 'aggressive' r1_pos = [0.500, 4.500] r3_pos = [7.5, 4] #r4_pos = [7.0, .5] buff_time = 0
def rules(bot, update): from rules import rules rules(bot, update)
def r3(cor, tot): ''' Parameter: The user's current score and the total number of problems asked so far are passed as arguments to dynamically display the score whenever the enters "S" or "s". The user will see their final score at the end. Purpose: This function prompts the user to solve one other random variable to a given right triangle (a side or an angle). The user will be given two random variables to a right triangle (which can be two side lengths or one side length and one angle). This function determines the ability of the user to do primary trigonometry. After each question the user will be notified whether they answered the question correctly or not. This function will allow the user see an up-to-date score or rules after each question if he/she wants to. Return: This function returns True if user answers correctly, and False otherwise ''' # List of possible given variables var = ['A', 'B', 'C', 'a', 'b'] # One of the givens have to be a side val1 = random.randint(11, 99) var1 = var[random.randint(0, 2)] # Decides whether the user has to solve for a side or to solve for an edge solveForSide = random.randint(0, 1) == 0 # Initialize second given variable, second given value, and unknown to None val2 = None var2 = None unknown = None if (solveForSide): # If user has to solve for a side, the user is given a side and an angle var2 = var[random.randint(3, 4)] val2 = random.randint(1, 89) # Selects a random side that is not the same as the given side unknown = var[random.randint(0, 2)] while (unknown == var1): unknown = var[random.randint(0, 2)] else: # If user has to solve for an angle, the user is given 2 sides var2 = var[random.randint(0, 2)] # Selects 2 distinct sides for given variables while (var2 == var1): var2 = var[random.randint(0, 2)] # If one of the given sides is the hypotenuse, it must be the longest side if (var2 == 'C'): val2 = random.randint(val1 + 1, 100) elif (var1 == 'C'): val2 = random.randint(10, val1 - 1) else: val2 = random.randint(10, 100) unknown = var[random.randint(3, 4)] # Formats the given variables and the variable the user has to solve for draw() print("Given: \n" + str(var1) + " = " + str(val1) + " units\n" + str(var2) + " = " + str(val2) + (" degrees" if solveForSide else " units")) print("Solve for " + str(unknown) + "\n") userAns = input("Enter your answer rounded to the nearest integer: ") # Keeps asking for input until user enters valid answer while not userAns.isdigit(): if userAns == "R" or userAns == "r": rules.rules() elif userAns == "S" or userAns == "s": print("\n" + "-" * 60) print("Your current score is " + str(cor) + " out of " + str(tot)) print("You are currently on question #" + str((tot) % 5 + 1) + " of round #" + str(math.ceil((tot + 1) / 5))) print("-" * 60, "\n") else: print("Your input is invaild! Please try again.\n") draw() print("Given: \n" + str(var1) + " = " + str(val1) + " units\n" + str(var2) + " = " + str(val2) + (" degrees" if solveForSide else " units")) print("Solve for " + str(unknown)) userAns = input("Enter your answer rounded to the nearest integer: ") userAns = int(userAns) ans = None # Solves for the unknown if (solveForSide): val2 = math.radians(val2) if (var1 == 'A'): if (var2 == 'a'): if (unknown == 'B'): ans = round(val1 / math.tan(val2)) else: ans = round(val1 / math.sin(val2)) else: if (unknown == 'B'): ans = round(val1 * math.tan(val2)) else: ans = round(val1 / math.cos(val2)) elif (var1 == 'B'): if (var2 == 'a'): if (unknown == 'A'): ans = round(val1 * math.tan(val2)) else: ans = round(val1 / math.cos(val2)) else: if (var2 == 'b'): if (unknown == 'A'): ans = round(val1 / math.tan(val2)) else: ans = round(val1 / math.sin(val2)) else: if (var2 == 'a'): if (unknown == 'A'): ans = round(val1 * math.sin(val2)) else: ans = round(val1 * math.cos(val2)) else: if (unknown == 'A'): ans = round(val1 * math.cos(val2)) else: ans = round(val1 * math.sin(val2)) else: if (var1 in 'AB' and var2 in 'AB'): A = val1 if (var1 == 'A') else val2 B = val2 if (var1 == 'A') else val1 if (unknown == 'a'): ans = round(math.degrees(math.atan(A / B))) else: ans = round(math.degrees(math.atan(B / A))) elif (var1 in 'BC' and var2 in 'BC'): B = val1 if (var1 == 'B') else val2 C = val2 if (var1 == 'B') else val1 if (unknown == 'a'): ans = round(math.degrees(math.acos(B / C))) else: ans = round(math.degrees(math.asin(B / C))) else: A = val1 if (var1 == 'A') else val2 C = val2 if (var1 == 'A') else val1 if (unknown == 'a'): ans = round(math.degrees(math.asin(A / C))) else: ans = round(math.degrees(math.acos(A / C))) # Outputs if user is correct or not if (userAns == ans): print("Congratulations! You are correct!\n") else: print("You are wrong! The correct answer is " + str(ans) + (" units" if solveForSide else " degrees") + ".\n") return userAns == ans
def r2(cor, tot): ''' Parameter: The user's current score and the total number of problems asked so far are passed as arguments to dynamically display the score whenever the enters "S" or "s". The user will see their final score at the end. Purpose: This function prompts the user to enter the roots of a randomly quadratic equation (f(x) = ax^2 + bx + c) given, after this function is invoked. The random quadratic equations given in this function will always have exactly 2 integer roots. This function determines the ability of the user to find the roots of a quadratic equation. After each question the user will be notified whether they answered the question correctly or not. This function will also allow the user see an up-to-date score or rules if he/she wants to. Return: This function returns True if user answers correctly, and False otherwise. ''' # Discriminant is originally defined as 0 (explained in next comment) d = 0 ''' The discriminant of a quadratic equation cannot be less than 0 (if discriminant is than 0 there are no real roots); in this function the discriminant cannot be equal to 0 (if the discriminant is 0, there will be only be one distinct real root); this function only asks the user to enter the roots of quadratic equations with exactly 2 distinct real roots ''' while d <= 0: # The standard form of quadratic equation is f(x) = ax^2 + bx + c # Coefficient a is between -100 and 100 and is randomly generated a = random.randint(-100,100) ''' Coefficient a in any quadratic equation cannot be equal to 0, thus coefficient a is randomly generated until it is not 0 ''' while a == 0: a = random.randint(-100,100) # Coefficient b is between -100 and 100 and is randomly generated b = random.randint(-100,100) # Coefficient c is between -100 and 100 and is randomly generated c = random.randint(-100,100) # Calculation of the discriminant (explanation of what the discriminant can be is explained previously) d = (b**2) - (4*a*c) # 2 roots of the quadratic equation are calculated rt1 = (-b-(math.sqrt(d)))/(2*a) rt2 = (-b+(math.sqrt(d)))/(2*a) ''' Determines whether the 2 roots of the quadratic equation are integers; the 2 roots must be integers in this program; Coefficients are generated randomly until the 2 roots of the quadratic equation are integers ''' while math.floor(rt1) != math.ceil(rt1) or math.floor(rt2) != math.ceil(rt2): # Discriminant is originally defined as 0 (explained in next comment) d = 0 ''' The discriminant of a quadratic equation cannot be less than 0 (if discriminant is than 0 there are no real roots); in this function the discriminant cannot be equal to 0 (if the discriminant is 0, there will be only be one distinct real root); this function only asks the user to enter the roots of quadratic equations with exactly 2 distinct real roots ''' while d <= 0: # The standard form of quadratic equation is f(x) = ax2 + bx + c # Coefficient a is between -100 and 100 and is randomly generated a = random.randint(-100,100) ''' Coefficient a in any quadratic equation cannot be equal to 0, thus coefficient a is randomly generated until it is not 0 ''' while a == 0 : a = random.randint(-100,100) # Coefficient b is between -100 and 100 and is randomly generated b = random.randint(-100,100) # Coefficient c is between -100 and 100 and is randomly generated c = random.randint(-100,100) # Calculation of the discriminant (explanation of what the discriminant can be is explained previously) d = (b**2) - (4*a*c) # 2 roots of the quadratic equation are calculated rt1 = (-b-(math.sqrt(d)))/(2*a) rt2 = (-b+(math.sqrt(d)))/(2*a) # Formatting the output of the quadratic equation to the user based on the values of coefficients (all cases considered) print("f(x) = ", end="") print(("-" if a<0 else "")+(str(abs(a)) if abs(a)>1 else "")+"x^2 ", end="") print(("- " if b<0 else "")+(("+ " if b>0 else "")+str(abs(b)) if abs(b)>1 else "")+("x " if b!=0 else ""), end="") print(("- " if c<0 else "")+(("+ " if c>0 else "")+str(abs(c)) if abs(c)>1 else "")) # User enters what they believe to be the two roots (separated by a comma) of the quadratic equation that is given (this is not a multiple choice quiz) string = input("Enter the 2 roots separated by a comma: ") # If the string the user enters has 1 comma and the length of the string is greater than 2 (used for error checking) if string.count(",") == 1 and len(string) > 2: stringSplit0 = string.split(",")[0] stringSplit1 = string.split(",")[1] # If the string after it is split has a length greater than 1 and has a negative sign (used for error checking) if len(stringSplit0) > 1 and stringSplit0[0] == '-': stringSplit0 = stringSplit0[1:] if len(stringSplit1) > 1 and stringSplit1[0] == '-': stringSplit1 = stringSplit1[1:] # Checks the input of the user and outputs the corresponding output (error checking and checking the user's input) while (string.count(",") != 1 or len(string) < 3 or (string.count(",") == 1 and not (stringSplit0.isdigit() and stringSplit1.isdigit()))): # If the user inputs "R" or "r" the rules of the quiz are outputted to the user if (string == "R" or string == "r"): rules.rules() # If the user inputs "S" or "s" the score of the quiz are outputted to the user elif (string == "S" or string == "s"): print("\n" + "-"*60) print("Your current score is " + str(cor) + " out of " + str(tot) + ".") print("You are currently on question #"+str((tot%5)+1)+" of round #"+str(math.ceil((tot+1)/5))) print("-"*60,"\n") # If the user inputs an invalid response, the user is prompted to enter what he/she thinks the are 2 roots else: print() print("Your input is invalid! Please try again.") print() # Formatting the output of the quadratic equation to the user based on the values of coefficients (all cases considered; coefficients determined previously) print("f(x) = ", end="") print(("-" if a<0 else "")+(str(abs(a)) if abs(a)>1 else "")+"x^2 ", end="") print(("- " if b<0 else "")+(("+ " if b>0 else "")+str(abs(b)) if abs(b)>1 else "")+("x " if b!=0 else ""), end="") print(("- " if c<0 else "")+(("+ " if c>0 else "")+str(abs(c)) if abs(c)>1 else "")) # User enters what they believe to be the two roots (separated by a comma) of the quadratic equation that is given (this is not a multiple choice quiz) string = input("Enter the 2 roots separated by a comma: ") # If the string the user enters has 1 comma and the length of the string is greater than 2 (used for error checking) if string.count(",") == 1 and len(string) > 2: stringSplit0 = string.split(",")[0] stringSplit1 = string.split(",")[1] # If the string after it is split has a length greater than 1 and has a negative sign (used for error checking) if len(stringSplit0) > 1 and stringSplit0[0] == '-': stringSplit0 = stringSplit0[1:] if len(stringSplit1) > 1 and stringSplit1[0] == '-': stringSplit1 = stringSplit1[1:] ans1, ans2 = map(int, string.split(",")) # Determining whether the two roots the user enters are correct # If the user enters both the correct roots if ans1 == rt1 and ans2 == rt2: print() # Outputs if the user enters both the 2 correct roots print("Congratulations! You are correct!") print() # Used to determine the score of the user return True # If the user enters both the correct roots elif ans2 == rt1 and ans1 == rt2: print() # Outputs if the user enters both the 2 correct roots print("Congratulations! You are correct!") print() # Used to determine the score of the user return True # If the user enters at least one wrong root else: print() # Outputs if the user enters at least one wrong root print("You are wrong!") # Outputs the 2 correct roots print("The 2 correct roots are:", str(int(round(rt1))) + " and " + str(int(round(rt2)))) print() # Used to determine the score of the user return False
def privmsg(self, user, channel, msg): # What happens when bot gets a message self.count = self.count + 1 swag = user.split('!') user = user.split('!', 1)[0] # Turn user!ident@host into nickname print("%s:<%s> %s" % (channel, user, msg)) # Show the message in console capsIntact = msg if channel == self.nickname: # Check if it's a private message pm = 1 else: pm = 0 # append(channel, user, msg) msg = msg.lower() if swag[1].lower() in self.opersh or channel.lower() == "#dino": # if the user is in the oper list admin = 1 else: admin = 0 if channel == "#thegrammarnaziboners": tstchan = 1 else: tstchan = 0 insult_ = True fibo_ = True choose_ = True dict_ = True wiki_ = True tz_ = True wz_ = True rule_ = True convert_ = True flist = {'insult': insult_, 'fibo': fibo_, 'choose': choose_, 'dict': dict_, 'wiki': wiki_, 'wz': wz_, 'tz': tz_, 'rule': rule_, 'convert': convert_} if msg.startswith("~die"): try: if admin == 1: if user.lower() in self.azi: print "Killed by %s" % user reactor.stop() else: self.notice(user, "Not amused") print("%s attempted to kill me!") except: self.notice(user, "You are not authorized to perform this command.") print("%s attempted to kill me!" % user) elif msg.startswith("~set ") and swag.lower() == "*****@*****.**": # self.sendLine("MODE %s +B %s" % (self.nickname, self.nickname)) self.mode(self.nickname, True, 'B', limit=None, user=self.nickname, mask=None) elif msg.startswith("~stop") and admin == 1: self.quit() elif msg.startswith("~id") and (admin == 1 or user.lower == "Kojiro"): self.msg("Nickserv", "identify hamsterbot %s" % self.password) elif msg.startswith("~ghost ") and admin == 1: msg = msg.split() self.msg("Nickserv", "ghost %s swagonball" % msg[1]) elif msg.startswith("~donut") and admin == 1: msg = msg.split(' ') try: if msg[1].isdigit(): #hopefully if i use a number it'll join that chan i = int(msg[1]) chan = self.chanlist[i] self.join(chan) #why doesnt this work nvm it does elif msg[1] == "joinall" or msg[1] == "all": for item in self.chanlist: self.join(item) else: self.join(msg[1]) except: if admin != 1: self.notice(user, "You are not authorized to perform this command.") else: self.say(channel, "-_-") elif msg.startswith("~bye"): try: if admin == 1: self.part(channel) except: self.notice(user, "You are not authorized to perform this command.") print("%s attempted to use command ~bye." % user) elif msg.startswith("~nick"): try: if admin == 1: msg = msg.split(' ') self.setNick(msg[1]) except: self.notice(user, "You are not authorized to perform this command.") print("%s tried to change my nick" % user) elif msg.startswith("~toggle ") and admin == 1: msg = msg.split() if len(msg) == 3: if flist.has_key(msg[1]): funct = msg[1].strip() if msg[2].strip() == "on" or msg[2] == '1': flist[funct] = True elif msg[2].strip() == 'off' or msg[2] == '0': flist[funct] = False elif msg[2] == 'not': flist[funct] = not flist[funct] else: self.notice(user, "Values accepted: on/off or 1/0") else: self.notice(user, "No function found with that name or function may not be switched on/off") elif len(msg) == 2: if msg[1] == 'help': self.notice(user, "The following functions may be switched on/off: insult, choose, convert, dict, fibo, rule, tz, wz, wiki") elif msg[1] == 'is_on': is_on = [] for key, value in flist.iteritems(): if value == True: is_on.append(key) self.notice(user, "The following functions are on: %r" % is_on) else: self.notice(user, "Toggle takes 2 arguments. Do ~toggle help for functions that may be toggled on/off") elif msg.startswith("~say ") and admin == 1: msg = msg[5:] self.say(channel, msg) elif msg.startswith("~note ") and (swag[1].lower()=="*****@*****.**"): msg = msg[6:] # bs.notes(str(msg)) self.notice(user, notes(str(msg))) elif msg.startswith(":prefixes "): msg = msg[10:] self.say(channel, whattodo(msg, user)) elif msg.startswith(".insult ") and insult_ == True: msg = msg.split(' ') #nick = msg[1] try: if msg[1].lower() in self.azi: self.say(channel, random.choice(azi_insults)) elif msg[1].lower() == "?roulette": self.say(channel, "%s, %s" % (user, random.choice(insults))) else: insult = "%s, %s" % (msg[1], random.choice(insults)) self.say(channel, insult) except IndexError: self.say(channel, random.choice(insults)) elif msg.startswith(".inslut") and flist['insult'] == True: msg = msg.split(' ') insult = "%s, %s" % (user, random.choice(insults)) self.say(channel, insult) elif msg.startswith(".halp") or msg.startswith(".help"): try: if admin == 1: self.notice(user, "Commands: .help, .insult <user>, .fibo, .convert <conversion> <numbers>, .gay, .rule <1-47>, .choose <option1, option2,...>, .dict <query>") self.notice(user, "Restricted commands: ~die, ~bye, ~donut <channel>, ~nick <newnick>") except: self.notice(user, "Commands: .help, .about, .insult <user>, .fibo, .convert <conversion> <numbers>") # elif msg.startswith("~~"): # msg = msg.strip("~~") # exec(msg) elif msg.startswith(".choose ") and flist['choose'] == True: msg = msg[8:] # re.sub("or*", '', msg) msg = msg.split(",") msg = random.choice(msg) words = msg.split(' ') if words[0] == 'or' and len(words) > 1: msg = msg.replace('or ','') self.msg(channel, "%s: %s" % (user, msg.strip())) # elif msg.startswith(".last"): # msg = msg[5:] # list = last(channel, msg) # for item in list: # self.msg(user, item) elif msg.startswith(".wiki ") and flist['wiki'] == True: #broken wikipedia feature msg = msg[6:] msg = msg.replace(' ', '_') self.msg(channel, str(wiki(str(msg)))) elif msg.startswith(".dict ") and flist['dict'] == True: #dictionary feature # msg = capsIntact msg = msg[6:] self.msg(channel, dict(msg)) elif msg.startswith(".tz ") and flist['tz'] == True: #timezone feature msg = msg[4:] self.msg(channel, tz(msg)) elif msg.startswith(".wz ") and flist['wz'] == True: #weatherbot feature msg = msg[4:] self.msg(channel, wz(msg)) elif msg.startswith(".gay"): self.msg(channel, "%s: http://blog.okcupid.com/index.php/gay-sex-vs-straight-sex" % user) elif msg.startswith(".rule ") and flist['rule'] == True: msg = msg.split() self.msg(channel, rules((msg[1].strip()))) elif msg.startswith(".fibo") and flist['fibo'] == True: msg = msg.split(' ') num = msg[1] i = fib2(int(num)) self.msg(channel, str(i)) elif msg.startswith(".convert") and flist['convert'] == True: msg = msg.split(' ') if convert(msg).startswith('S') or convert(msg).startswith('N'): if '::' in convert(msg): resp = convert(msg).split('::') self.notice(user, resp[0]) self.notice(user, resp[1]) else: self.notice(user, convert(msg)) elif pm == 1: self.notice(user, convert(msg)) else: self.msg(channel, convert(msg))
def __init__(self): print("Proxy") self.proxyStatus = False self.rule = rules() super().__init__()
def calculate_pearson_correlation_coefficient_star(bas_dataset, classification_file, rule_set, rule_number): #calculate pearson correlation coefficient * for a non-numerical attribute of the users dataset if 'users' in bas_dataset and ((rule_number in [2,3,4,9] and rule_set == 'camsani_calzolari') or (rule_number in [1,4] and rule_set == 'van_den_beld')): attribute = rules.attributes(rule_set, rule_number) df_dataset = pandas.read_csv(bas_dataset) attribute_list = df_dataset[attribute].values attr_values = [] for attr in attribute_list: if rule_number == 4: rule_output = rules.rules(rule_set, rule_number, [attr, df_dataset[attribute]]) else: rule_output = rules.rules(rule_set, rule_number, attr) if rule_output == 1: number_satisfied = 1 else: number_satisfied = 0 attr_values.append(number_satisfied) df_attr = pandas.DataFrame(attr_values, columns =[attribute]) df_classification = pandas.read_csv(classification_file) df_class = df_classification['class'] df_pcc_star = pandas.concat([df_attr, df_class], axis=1) pearson_correlation_coefficient_star = df_pcc_star.corr(method='pearson') #calculate pearson correlation coefficient * for a numerical attribute of the users dataset elif 'users' in bas_dataset: attribute = rules.attributes(rule_set, rule_number) df_dataset = pandas.read_csv(bas_dataset) df_attribute = df_dataset[attribute] df_numerical_attribute = df_attribute.fillna(0) df_classification = pandas.read_csv(classification_file) df_class = df_classification['class'] df_pcc_star = pandas.concat([df_numerical_attribute, df_class], axis=1) pearson_correlation_coefficient_star = df_pcc_star.corr(method='pearson') #calculate pearson correlation coefficient * for an attribute of the tweets dataset else: attribute = rules.attributes(rule_set, rule_number) df_dataset = pandas.read_csv(bas_dataset) user_id_list = list(set(df_dataset['user_id'].values)) df_classification = pandas.read_csv(classification_file) attr_values = [] real_classes = [] for user_id in user_id_list: df_user = df_dataset.loc[df_dataset['user_id'] == user_id] attribute_list = df_user[attribute].values attribute_value = attribute_list[0] number_satisfied = 0 if rule_number == 22: number_satisfied = len(df_user[attribute].unique()) elif rule_number == 3 and rule_set == 'social_bakers': number_satisfied = df_user[attribute].value_counts().max() else: for attr in attribute_list: rule_output = rules.rules(rule_set, rule_number, attr) if rule_output == 1: number_satisfied += 1 attr_values.append(number_satisfied) df_class = df_classification.loc[df_classification['id'] == user_id] real_class = df_class['class'].values real_classes.append(real_class) df_attr = pandas.DataFrame(attr_values, columns =[attribute]) df_cl = pandas.DataFrame(real_classes, columns =['class']) df_pcc_star = pandas.concat([df_attr, df_cl], axis=1) pearson_correlation_coefficient_star = df_pcc_star.corr(method='pearson') return pearson_correlation_coefficient_star
def analyzeAV(arch, av, os, web, dir): # rav[] store CWSS values from rules rav = [] for comp in av: #attributesbyrules rav.append(rules.rules(comp)) #loadAttCWE has new features CWE = static.loadAttCWE() # sav[] store individual attribute scores from rav[] sav = [] #create the minidom document doc = Document() #create the <root> base element root = doc.createElement("Attack_Vector") doc.appendChild(root) for j in range(0, len(av)): "" sav.append(rav[j]) #Scores for non top25 weaknesses s = [sav[j][0],sav[j][1],sav[j][2],sav[j][3],sav[j][4],sav[j][5],sav[j][6],sav[j][7],sav[j][8],sav[j][9],sav[j][10],\ sav[j][11],sav[j][12],sav[j][13],sav[j][14],sav[j][15],sav[j][16],sav[j][17],sav[j][18]] #Scores for top25 weaknesses s25 = [sav[j][19],sav[j][20],sav[j][21],sav[j][22],sav[j][23],sav[j][24],sav[j][25],sav[j][26],sav[j][27],sav[j][28],\ sav[j][29],sav[j][30],sav[j][31],sav[j][32],sav[j][33],sav[j][34],sav[j][35],sav[j][36],sav[j][37]] # s = ["%.2f" % elem for elem in s] s25 = ["%.2f" % elem for elem in s25] # match = {} ntchos = {} match, ntchos = subAV(av[j].cLang, s, s25, CWE) # component = doc.createElement("Component") component.setAttribute("name", av[j].cName) for k in match.keys(): elemcwe = doc.createElement("CWE") id = "CWE-" + k #We select weaknesses related to the operating system involved ("Unix Linux Mac"), so far! if (os == "ULM" and (k not in listOS)): #We select weaknesses NOT related to web applications or services here if ((not web) and (k not in listWEB)): elemcwe.setAttribute("id", id) name = ntchos[k][0] elemcwe.setAttribute("name", name) elemcwe.setAttribute("top25", ntchos[k][1]) elemcwe.setAttribute("childof", ntchos[k][2]) elemcwe.setAttribute("os", ntchos[k][3]) component.appendChild(elemcwe) "" attrib = doc.createElement("Attribute") for l in range(0, len(match[k])): if ((l % 2) == 0): safeatt = match[k][l] else: valueatt = match[k][l] attrib.setAttribute(safeatt, valueatt) elemcwe.appendChild(attrib) component.appendChild(elemcwe) root.appendChild(component) avfile = "workspace/" + dir + "/xml/" + arch + ".xml" file = open(avfile, "wb") try: file.write(doc.toprettyxml(indent=" ")) finally: file.close() return 0
def home(): font=cv2.FONT_HERSHEY_PLAIN #global text option_window=np.zeros((950,1000,3),np.uint8) option_window[:]=(100,0,50) #video_capture.set(cv2.CAP_PROP_FRAME_WIDTH, 160) #video_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 120) cap= cv2.VideoCapture(0) #cap.set(cv2.CAP_PROP_FRAME_WIDTH, 950) #cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1000) board=np.zeros((600,1000,3),np.uint8) keyboard_type=np.zeros((950,1000,3),np.uint8) detector =dlib.get_frontal_face_detector() predictor=dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") def midpoint(p1,p2): return ((p1.x+p2.x)//2,(p2.y+p2.y)//2) font=cv2.FONT_HERSHEY_PLAIN def get_eye_gaze_ratio(eye_points, facial_landmarks): #gaze detection left_eye_region=np.array([(facial_landmarks.part(eye_points[0]).x,facial_landmarks.part(eye_points[0]).y), (facial_landmarks.part(eye_points[1]).x,facial_landmarks.part(eye_points[1]).y), (facial_landmarks.part(eye_points[2]).x,facial_landmarks.part(eye_points[2]).y), (facial_landmarks.part(eye_points[3]).x,facial_landmarks.part(eye_points[3]).y), (facial_landmarks.part(eye_points[4]).x,facial_landmarks.part(eye_points[4]).y), (facial_landmarks.part(eye_points[5]).x,facial_landmarks.part(eye_points[5]).y)],np.int32) height,width,_=frame.shape mask=np.zeros((480,640),np.uint8) cv2.polylines(frame,[left_eye_region],True,255,2) cv2.fillPoly(mask,[left_eye_region],255) eye=cv2.bitwise_and(gray,gray,mask=mask) min_x=np.min(left_eye_region[:,0]) max_x=np.max(left_eye_region[:,0]) min_y=np.min(left_eye_region[:,1]) max_y=np.max(left_eye_region[:,1]) gray_eye= eye[min_y:max_y,min_x:max_x] _,threshold_eye=cv2.threshold(gray_eye,70,255,cv2.THRESH_BINARY) height,width=threshold_eye.shape left_side_threshold=threshold_eye[0:height,0:width//2] left_side_white=cv2.countNonZero(left_side_threshold) right_side_threshold=threshold_eye[0:height,width//2:width] right_side_white=cv2.countNonZero(right_side_threshold) #zeros are black gaze_ratio=0 try: gaze_ratio=left_side_white/right_side_white except ZeroDivisionError: pass return gaze_ratio def recta(output_index,light): #output_index=self.output_index if output_index==0: x=(200,440) #rules y=(250,490) elif output_index==2: x=(700,440) # 0-9 y=(750,490) elif output_index==1: x=(495,670) #a-0 y=(445,720) else: x=(495,200) #p-z y=(445,250) if light is True: cv2.rectangle(option_window,x,y,(255,255,255),255,-1) else: cv2.rectangle(option_window,x,y,(255,0,0),255,-1) #text settings cv2.putText(option_window,"Rules",(190,460),font,3,(0,0,0),3) cv2.putText(option_window,"0-9",(690,460),font,3,(0,0,0),3) cv2.putText(option_window,"A-O",(425,695),font,3,(0,0,0),3) cv2.putText(option_window,"P-Z",(425,225),font,3,(0,0,0),3) #counters frames=0 output_index=0 blinking_frames=0 #text="" while True: _,frame=cap.read(0) frames +=1 #keyboard[:]=(0,0,0) gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) faces=detector(gray) #active_letter=keys_set_1[letter_index] for face in faces: #x,y=face.left(),face.top() #x1,y1=face.right(),face.bottom() #print(face) #cv2.rectangle(frame,(x,y),(x1,y1),(0,255,0)) landmarks=predictor(gray,face) #print(landmarks.part(36)) #left eye top=midpoint(landmarks.part(37),landmarks.part(38)) bottom=midpoint(landmarks.part(41),landmarks.part(40)) leftpoint=(landmarks.part(36).x,landmarks.part(36).y) rightpoint=(landmarks.part(39).x,landmarks.part(39).y) #hor_line=cv2.line(frame,leftpoint,rightpoint,(0,255,0),2) #ver_line=cv2.line(frame,top,bottom,(0,255,0),2) leftver_line_length = hypot((top[0]-bottom[0]),(top[1]-bottom[1])) lefthor_line_length = hypot((leftpoint[0]-rightpoint[0]),(leftpoint[1]-rightpoint[1])) ratio1=lefthor_line_length/leftver_line_length #right eye leftpoint1=(landmarks.part(42).x,landmarks.part(42).y) rightpoint1=(landmarks.part(45).x,landmarks.part(45).y) topr=midpoint(landmarks.part(43),landmarks.part(44)) bottomr=midpoint(landmarks.part(47),landmarks.part(46)) #hor_line1=cv2.line(frame,leftpoint1,rightpoint1,(0,255,0),2) #ver_line1=cv2.line(frame,topr,bottomr,(0,255,0),2) rightver_line_length = hypot((topr[0]-bottomr[0]),(topr[1]-bottomr[1])) righthor_line_length = hypot((leftpoint1[0]-rightpoint1[0]),(leftpoint1[1]-rightpoint1[1])) ratio2=righthor_line_length/rightver_line_length ratio=(ratio2+ratio1)/2 #cv2.putText(frame,str(ratio),(50,150),font,3,(255,0,0)) #print(leftver_line_length) if ratio>4.8: #cv2.putText(frame,str(letter_index),(400,150),font,3,(255,0,0)) cv2.putText(frame,"BLINKING",(50,150),font,3,(0,0,255)) #print(keys_set_1[letter_index]) blinking_frames+=1 frames-=1 if blinking_frames==3: #text += active_letter playsound("get-outta-here.mp3") if output_index==0: rules() elif output_index==1: cap.release() cv2.destroyAllWindows() omg() home() elif output_index==2: cap.release() cv2.destroyAllWindows() num() home() else: cap.release() cv2.destroyAllWindows() omgpz() home() #time.sleep(1) # print(keys_set_1[letter_index]) # print(text) # print(active_letter) else: blinking_frames=0 gaze_ratio_left_eye=get_eye_gaze_ratio([36,37,38,39,40,41],landmarks) gaze_ratio_right_eye=get_eye_gaze_ratio([42,43,44,45,46,47],landmarks) gaze_ratio=(gaze_ratio_left_eye+gaze_ratio_right_eye)/2 cv2.putText(frame,str(gaze_ratio),(50,300),font,2,(0,0,255),3) if gaze_ratio<0.1: cv2.putText(frame,"right",(50,200),font,2,(0,0,255),3) elif gaze_ratio>1: cv2.putText(frame,"left",(50,200),font,2,(0,0,255),3) #print(frames) if frames==26: output_index=output_index+1 frames=0 if output_index==4: output_index=0 for i in range(4): if i==output_index: light=True else: light=False recta(i,light) #note i #print(i,light) #print(light,output_index) #threshold_eye=cv2.resize(threshold_eye,None,fx=8,fy=8) #keyboard1=cv2.resize(keyboard,None,fx=0.5,fy=0.5) #cv2.imshow("t",threshold_eye) #cv2.imshow("left",left_side_threshold) #cv2.imshow("right",right_side_threshold) #joint_keyboard=np.vstack((board,keyboard)) #joint_keyboard1=cv2.resize(joint_keyboard,None,fx=0.5,fy=0.5) #final_keyboard=np.concatenate((joint_keyboard1,frame),axis=) option_window2=cv2.resize(option_window,(600,700)) ff=cv2.resize(frame,(600,700)) #cv2.imshow("fdd",ff) #cv2.imshow("f",frame) #cv2.imshow("keyboardfirst",keyboard_type) #cv2.imshow("keyboard",keyboard1) #cv2.imshow("board",board) #cv2.imshow("key",joint_keyboard1) joined_frames=np.hstack((ff,option_window2)) cv2.imshow("home",joined_frames) key = cv2.waitKey(1) if key==27: #pressing esc key break cap.release() cv2.destroyAllWindows()
from HookManager.HookCollection import HookCollection from rules import rules def modify(packet): testHook = Hook("Test",True,"Neat!",2,"testHook.py") hooks = [] hc = HookCollection("testCollection",0,True,"Test hook coll.",hooks) hc.addHook(testHook) newpkt = hc.executeHookSequence(packet) pkt = IP(packet.get_payload()) #converts the raw packet to a scapy compatible string #modify the packet all you want here #packet.set_payload(str(pkt)) #set the packet content to our modified version packet.accept() #accept the packet rule = rules() rule.set() nfqueue = NetfilterQueue() #1 is the iptabels rule queue number, modify is the callback function nfqueue.bind(1, modify) try: print ("[*] waiting for data") nfqueue.run() except KeyboardInterrupt: rule.flush() pass