class Test(object): # default f1 = Rule("f1", to_field="__f1", required=False, allowed_none=True) f2 = Rule("f2", to_field="__f2", required=False, allowed_none=False) f3 = Rule("f3", to_field="__f3", required=True, allowed_none=False) f4 = Rule("f4", to_field="__f4", required=True, allowed_none=True)
def __init__(self, rules: list, implications: list, membership_function: dict, domain: tuple): self.implication = implications self.membership_function = membership_function self.domain = domain AggregationMethods.__init__(self, Mamdani.consequent_filter) self.rules = [Rule(item.split(), max, min, lambda x: 1-x) for item in rules]
def execute(self): ListRules().execute() operator = input( "Choose operator to apply to rules(number).\n1. Any \n2. All\nChoose: " ) try: operator = int(operator) except ValueError: print("Choose numbers\n 1. Any \n2. All\n ") rules_to_apply = [] while True: ListRules().execute() rule = input( "Rule Name to apply or done in case you wish to execute now: ") rule = rule.strip() if rule == "done": break if self.fetch_rule(rule): if rule not in rules_to_apply: rules_to_apply.append(rule) else: print("Could not find rule") ListAction().execute() action_name = input("Action to apply. Choose by name: ") action_types = [ action.action_name for action in ActionType.__subclasses__() ] if action_name not in action_types: print("Could not find the action") if action_name == 'move': move_folder = input("Where should I move the emails: ") else: move_folder = None result_ids = set() for rule in rules_to_apply: rule = Rule(rule) rule.from_json(rule.rule_file) result = rule.fetch_for_rule() new_result_ids = set([message.gmail_id for message in result]) if operator == 1: result_ids.union(new_result_ids) else: if len(result_ids) == 0: result_ids = new_result_ids else: result_ids.intersection(new_result_ids) actions = [ action for action in ActionType.__subclasses__() if action.action_name == action_name ] action = actions[0] action().apply(result_ids, move_folder=move_folder)
def backup(args): with open(args.config) as config_file: config = json.load(config_file) rule = Rule(config) if args.dryrun: # dryrun does not work anymore ('it is dry-run now) raise NotImplementedError('dryrun does not work anymore (it is dry-run now)') rule.options.dryrun = args.dryrun now = datetime.datetime.now() rsync_command = ['rsync'] + rule.get_optional_args(now) + rule.get_positional_args(now) # create dirs fro log files success_filepath = rule.log.get_sucess_filepath(now) if not args.debug and success_filepath: make_dirpath(success_filepath) progress_filepath = rule.log.get_progress_filepath(now) if args.verbose or args.debug or not progress_filepath: progress_file = sys.stdout else: make_dirpath(progress_filepath) progress_file = open(progress_filepath, "w") error_filepath = rule.log.get_error_filepath(now) if args.verbose or args.debug or not error_filepath: error_file = sys.stderr else: make_dirpath(error_filepath) error_file = open(error_filepath, 'w') if error_filepath else PIPE # process if args.debug: print(' '.join(rsync_command)) else: rsync_process = Popen(rsync_command, stdout=progress_file, stderr=error_file) rsync_process.wait() # some cleaning if progress_filepath and exists(progress_filepath): remove(progress_filepath) if error_filepath and exists(error_filepath): is_errors = not stat(error_filepath).st_size == 0 if not is_errors: remove(error_filepath) user_message = 'sucessfull save of {}.'.format(rule.source.dirpath) else: with open(error_filepath, 'r') as error_file: last_error = error_file.readlines()[-1].decode() user_message = 'finished with errors on save of {}: {}'.format(rule.source.dirpath, last_error) else: user_message = 'done' notify_command = ['synodsmnotify', '@administrators', 'Backup {}'.format(basename(realpath(rule.source.dirpath))), user_message] call(notify_command) logging.debug('done')
def __init__(self, learning_rate, no_rules, max_iter): self.learning_rate = learning_rate self.max_iter = max_iter self.rules = [Rule() for _ in range(no_rules)] self.samples = [ SampleDataFunction(x, y) for x in range(-4, 4) for y in range(-4, 4) ] self.sum_w = self.sum_wz = 0
def test_metaclass(self): rule = Rule("Field") class Test(object): __metaclass__ = MetaRules field = rule self.assertTrue(hasattr(Test, "_fields")) self.assertEqual(Test._fields, {'field': rule}) self.assertEqual(Test()._fields, {'field': rule})
def __initialize_rules(self): self.rules = [] rules = [] try: with open("rules.json") as rules_file: rules = json.loads(rules_file.read()) except: pass for rule in rules: self.rules.append(Rule(rule))
def execute(self): list_rule = ListRules() print("The list of rules to choose from, Please choose the name:") list_rule.execute() rule = input("Describe the rule: ") rule_file = rule + '.json' if not os.path.isfile(rule_file): print("Could not find the rule by the name {}".format(rule)) exit() rule = Rule(rule).from_json(rule_file) print(rule.render())
def add_builtins(rules_db): rules_db.add_rule( Rule([], expression_from_list([ Variable("X"), rules_db.add_constant_by_name("is"), Variable("X") ]), rules_db.add_constant_by_name("is_rule"), "(built-in)", rules_db)) rules_db.add_rule(RuleIsNot(rules_db)) rules_db.add_rule(RuleAtom(rules_db)) rules_db.add_rule(RuleNewAtom(rules_db))
def update_rules(message): global rules rules = message rules_given_id.clear() print("update rules given id {}".format(rules_given_id)) for r in rules: print(r) rule = Rule(r, enabled=r['enabled']) print(rule.root) print(rule.evaluate()) rule.execute() print('updating rules') print(rules) update_admin() # to send the new rules status
def update_admin(): devices = [{'id': x, 'state': device.get_state(), 'state_label': device.get_state_label(), 'is_actuator': isinstance(device, Actuator), 'type': device.type } for x, device in device_ids.items()] builder_rules = [] for device in device_ids.values(): builder_rules.append(device.build_rule()) from state import device_names for r in rules: r['status'] = Rule(r, enabled=r['enabled']).evaluate() for admin_id in app.admin_id: emit('update', {'devices': devices, 'builder_rules': builder_rules, 'rules': rules, 'device_names': device_names}, room=admin_id)
def __init__(self, list_of_players): ''' @param: list_of_players: a list of players @return: none ''' self.lastgame_round_players = list_of_players self.players = list_of_players self.rule_checker = Rule() self.board = Board([], []) self.loser = [] self.log = [] if len(list_of_players) > 5 or len(list_of_players) < 3: raise Exception("Incorrect number of players") colors = ["white", "black", "red", "green", "blue"] self.avatar_player = {} for i in range(len(list_of_players)): self.avatar_player[list_of_players[i]] = Avatar(colors[i], None)
def generate_rules(self): '''Generate rules from frequent itemsets''' # start from 2-elements itemsets for level in self.itemsets[1:]: for itemset in level: subsets = Rule.get_subsets(itemset) for antecedent in subsets: consequent = itemset.difference(antecedent) if antecedent and consequent: rule_support = self.support[itemset] rule_confidence = rule_support / self.support[antecedent] if rule_confidence > self.min_confidence: self.rules.append(Rule(antecedent, consequent, rule_support, rule_confidence)) self.rules.sort(key=lambda rule: rule.confidence)
def get_rules(self): '''Generate association rules from frequent itemsets''' rules = [] for itemset in self.itemsets: # if itemset is one-element, then antecedent or consequent # will be empty, so skip if len(itemset) > 1: subsets = Rule.get_subsets(itemset) for antecedent in subsets: consequent = itemset.difference(antecedent) if antecedent and consequent: rule_support = self.get_support(itemset) rule_confidence = rule_support / self.get_support( antecedent) if rule_confidence > self.min_confidence: rules.append( Rule(antecedent, consequent, rule_support, rule_confidence)) rules.sort(key=lambda rule: rule.confidence) return rules
def test(definitions): from rules import Rule definitions.set_attribute('Plus', 'Flat') definitions.set_attribute('Plus', 'Orderless') definitions.set_attribute('g', 'Orderless') eval = Evaluation(Symbol('unused'), definitions) #expr = 'Plus[a,b,c,d,e,f,g,h,i,1,2,3]' #expr = 'a+b+a+e+a+b+a+e+a+b+a+e+a+b+a+e+f' #expr = 'a+b+c+d+e+f+g+h+i+j+k+l+a+b' #pattern = 'x_+x_+b+c+d+e+f+g+h+i+j+k+l' #expr = 'a+b+c+d+e+f+g+h+i+j+k+l+a+b+b+1+2+3' #pattern = 'x_+x_+c+d+e+f+g+h+i+j+k+l' #pattern = 'Plus[x_]' #expr = 'g[a+b+c+d+e,b,e,d,c,a]' #pattern = 'g[x__+y_,y_,x__]' #expr = 'g[a+b+c+d+e,b]' #pattern = 'g[x__+y_,y_]' #expr = 'a+a+b' #pattern = 'x__+x__' #expr = 'a+b+c' #pattern = 'x_+y_' expr = 'Format[a+b]' pattern = 'Format[Plus[items__]]' #expr = 'a*b+c*d+e*f+g*h+i*j+k*l+m*n' #pattern = 'a_*x_+b_*x_+a_*x_+b_*x_' expr = parse(expr).evaluate(eval) pattern = parse(pattern).evaluate(eval) print expr print pattern rule = Rule(pattern, parse('3')) #evaluation = Evaluation(Expression) print '%s' % rule.apply(expr, eval)
def result(): delete_target_dir('./static') os.mkdir('./static') # 清洗数据 if not os.path.exists('./datas/1.xlsx'): data = {'code': 0, 'info': '未上传excel'} return jsonify(data) from clean_data import Duty duty = Duty() datas = duty.get_duty_datas() # pprint(datas) with open('./datas/results.json', 'w', encoding='utf-8') as f: f.write(json.dumps(datas, ensure_ascii=False)) # 执行规则 from rules import Rule Rule() # 返回api结果 data = {'code': 1, 'info': 'http://192.168.10.129:5000/static/考勤结果.xlsx'} print('执行完毕') return jsonify(data)
class TestRules(Rules): id_field = Rule("Id", required=True)
class TestRules(Rules): id_field = Rule("Id", allowed_none=False)
class TestRules(Rules): id_field = Rule("Id", required=False)
return num_bags else: cumul = num_bags for element in content: num_contents = int(content[element]) jander = (num_bags * num_contents) element_rule = [ item for item in rules if item.get_bag() == element ][0] cumul += get_num_bags(jander, element_rule, rules) #print ("Value of cumul afer processing {}: {}".format(element, cumul)) #print ("Value of cumul {}".format(cumul)) return cumul def solve_2(bag_type, rules): shiny_gold_rule = [item for item in rules if item.get_bag() == bag_type][0] contained_bags = get_num_bags(1, shiny_gold_rule, rules) - 1 print("The number of bags within a '{}' is {}".format( bag_type, contained_bags)) if __name__ == '__main__': with open('Rules.txt') as f: all_rules = [Rule(line.strip()) for line in f.readlines()] bag_type = "shiny gold" solve_1(bag_type, all_rules) solve_2(bag_type, all_rules)
from simulator import Simulator from rules import Rule from conseedset import StartBoardGenerator import numpy as np from collections import namedtuple from settings import Settings from frame import * from menu import * settings = Settings('settings.json') isSuccessfullyLoadS = settings.loadSettings() if not isSuccessfullyLoadS: settings.consInit() settings.saveSettings() rule = Rule() isSuccessfullyLoadS = rule.jsonToObj(settings.ruleFN) if not isSuccessfullyLoadS: rule.consInit() rule.objToJson(settings.ruleFN) seed = StartBoardGenerator(settings.seedFN) isSuccessfullyLoadS = seed.fileLoad() if not isSuccessfullyLoadS: seed.consInit() seed.fileSave() def startSim(): sim = Simulator(rule, seed.square_face) sim.setSeed(seed.board)
def __init__(self): self.rules = [] self.state = fsm_states.INIT self.signal = None # Components: self.keypad = Keypad() self.ledboard = Ledboard() self.kpc = KPC(self.keypad, self.ledboard) # Setting up rules: # Init: self.add_rule( Rule(fsm_states.INIT, fsm_states.READ, any_signal, self.kpc.init_password_entry)) # Read: # On digits, simply add it to password self.add_rule( Rule(fsm_states.READ, fsm_states.READ, signal_is_digit, self.kpc.add_signal_to_password_input)) # On *, password is complete. Verify and write a overload signal to # memory self.add_rule( Rule(fsm_states.READ, fsm_states.VERIFY_READ, "*", self.kpc.verify_login)) # Else return to init self.add_rule( Rule(fsm_states.READ, fsm_states.INIT, any_signal, self.kpc.reset_password_field)) # Verify: # Verify password by getting a Y signal from the agent. Might change # action later? self.add_rule( Rule(fsm_states.VERIFY_READ, fsm_states.ACTIVE, "Y", self.kpc.do_nothing)) # ELse return to read self.add_rule( Rule(fsm_states.VERIFY_READ, fsm_states.INIT, any_signal, self.kpc.reset_password_field)) # TODO Er det ikke tilbake til init her? Er jo feil passord... # From Active to 1) SET_PW, 2) LED, 3) LOGOUT: change_password_button = 9 # On ^this button, change state to set_pw self.add_rule( Rule(fsm_states.ACTIVE, fsm_states.SET_PW, change_password_button, self.kpc.init_password_entry)) # On a digit between 0 and 5, change state to LED and save which LED # that has been chosen self.add_rule( Rule(fsm_states.ACTIVE, fsm_states.LED, signal_is_digit_between_0_and_5, self.kpc.set_led)) # On "#", change state to logout self.add_rule( Rule(fsm_states.ACTIVE, fsm_states.LOGOUT, "#", self.kpc.do_nothing)) # 1) SET_PW: # On digit, add this to password //TODO: HVORFOR TO HER? self.add_rule( Rule(fsm_states.SET_PW, fsm_states.SET_PW, signal_is_digit, self.kpc.add_signal_to_password_input)) self.add_rule( Rule(fsm_states.SET_PW, fsm_states.SET_PW, signal_is_digit, self.kpc.add_signal_to_password_input)) # On *, check if password is valid and write to memory if it is self.add_rule( Rule(fsm_states.SET_PW, fsm_states.VERIFY_PWCHANGE, "*", self.kpc.verify_password_change)) # Else, return to active TODO: AGAIN STRANGE WITH THE ELSE-SENTENCE, # FROM METHOD IN KPC? self.add_rule( Rule(fsm_states.VERIFY_PWCHANGE, fsm_states.ACTIVE, any_signal, self.kpc.do_nothing)) # 2) LED: TODO: ISNT LINE 74 UNNECESSARY, IS THE SAME IN LINE 59? BETTER WITH ADD_DURATION_DIGIT # On a digit between 0 and 5, change state to LED and save which LED # that has been chosen self.add_rule( Rule(fsm_states.LED, fsm_states.LED, signal_is_digit_between_0_and_5, self.kpc.set_led)) # On *, confirm LED TODO: MOST BE ADD_DURATION_DIGIT(SYMBOL) ON 74 self.add_rule( Rule(fsm_states.LED, fsm_states.TIME, "*", self.kpc.do_nothing)) # Time: TODO: JUST KIDDING, HERE IS TIME... BUT WHY THE DOUBLE UP OF SET_LED? # On digit, add that value to duration self.add_rule( Rule(fsm_states.TIME, fsm_states.TIME, signal_is_digit, self.kpc.add_duration_digit)) # On *, activate the chosen LED for the chosen amount of seconds self.add_rule( Rule(fsm_states.TIME, fsm_states.ACTIVE, "*", self.kpc.activate_led)) # Logout # On # logout completely and return to init phase self.add_rule( Rule(fsm_states.LOGOUT, fsm_states.INIT, "#", self.kpc.power_down)) # CHANGED TO SHUTDOWN_FLASH HERE # Else, return to active TODO WHEN DOES THIS HAPPEN? self.add_rule( Rule(fsm_states.LOGOUT, fsm_states.LOGOUT, any_signal, self.kpc.do_nothing))
class Test(Rules): field = Rule("Id")
def __init__(self, name, strategy): self.strategy = strategy self.rule_checker = Rule() self.name = name
def execute(self): field = input("Add the input field out of (from/to/subject/date): ") if (field == "from" or field == "to"): field = field + "_email" if field not in ["from_email", "to_email", "subject", "date"]: print("Could not recognize the option. Exiting") exit() # field_value = input("Value of the field: ") used_predicate = None if field in ['from_email', 'to_email', 'subject']: options_string = "" used_predicate = STRING_PREDICATES for num, option in enumerate(STRING_PREDICATES, 1): options_string += "%s. %s " % (num, option) elif field in ['date']: options_string = "" used_predicate = DATE_PREDICATES for num, option in enumerate(DATE_PREDICATES, 1): options_string += "%s. %s " % (num, option) choice = input("Choose the predicate {}: ".format(options_string)) try: choice = int(choice) except ValueError: print("Need an integer choice") exit() if (choice > len(used_predicate) or choice < 0): print("Choice not found") exit() predicate = used_predicate[choice - 1] comparison_value = input("Value to compare to: ") name_rule = input("Name for the rule: ") action = input( "Choose action (1. Mark as Read/2. Mark as Unread/3. Move): ") try: action = int(action) except ValueError: print("Need an integer choice") exit() if (action <= 0 or action >= 3): print("Action not found") exit() if action == 1: action = "mark_as_read" elif action == 2: action = "mark_as_unread" elif action == 3: action = "move" folder = input("name of folder to move to") rule = Rule(name_rule) rule.add_field(field) # rule.add_field(field, field_value) rule.add_predicate(predicate) rule.add_value(comparison_value) if (action == "mark_as_read" or action == "mark_as_unread"): rule.add_action(action) if action == "move": rule.add_action(action, folder) rule.write_to_file()
from conseedset import StartBoardGenerator import numpy as np from collections import namedtuple from printer import * from menu import * from settings import Settings menu = Menu(True) settings = Settings('settings.json') isSuccessfullyLoadS = settings.loadSettings() if not isSuccessfullyLoadS: settings.consInit() settings.saveSettings() rule = Rule() isSuccessfullyLoadS = rule.jsonToObj(settings.ruleFN) if not isSuccessfullyLoadS: rule.consInit() rule.objToJson(settings.ruleFN) seed = StartBoardGenerator(settings.settingsFN) isSuccessfullyLoadS = seed.fileLoad() if not isSuccessfullyLoadS: seed.consInit() seed.fileSave() sim = Simulator(Rule(), seed.square_face) sim.setSeed(seed.board) printer = BlenderPrinter(settings.pictureDN) printer.printFrame(sim.getCells(), 0)
from rules import Rule, union import brightness as br import distance as dist import power if (__name__ == '__main__'): # main function goes here # brightness 0 - 5500 lux # distance 0 - 750 cm input_dist = float(input('Distance: ')) input_brightness = float(input('Brightness: ')) rule_output = [] y = 0 yx = 0 rule1 = Rule(dist.very_far(input_dist), br.dark(input_brightness)) rule_output.append(rule1.fuzzificate(1)) rule2 = Rule(dist.very_far(input_dist), br.low_brightness(input_brightness)) rule_output.append(rule2.fuzzificate(2)) rule3 = Rule(dist.very_far(input_dist), br.medium_brightness(input_brightness)) rule_output.append(rule3.fuzzificate(3)) rule4 = Rule(dist.far(input_dist), br.dark(input_brightness)) rule_output.append(rule4.fuzzificate(4)) rule5 = Rule(dist.far(input_dist), br.low_brightness(input_brightness)) rule_output.append(rule5.fuzzificate(5)) rule6 = Rule(dist.far(input_dist), br.medium_brightness(input_brightness)) rule_output.append(rule6.fuzzificate(6)) rule7 = Rule(dist.not_far(input_dist), br.medium_brightness(input_brightness))
def test_representation(self): self.assertEqual(repr(Rule("ofLife")), b'<Rule: ofLife>')
def set_ownvalue(self, name, value): from expression import Symbol from rules import Rule self.add_rule(name, Rule(Symbol(name), value))
import time from presets import ConwayPatterns from rules import Rule, Condition from world import World # Define rules rule1 = Rule(1, [Condition(1, "LESS", 2)], 0) rule2 = Rule(1, [Condition(1, "GREATER_EQUAL", 2), Condition(1, "LESS", 4)], 1) rule3 = Rule(1, [Condition(1, "GREATER_EQUAL", 4)], 0) rule4 = Rule(0, [Condition(1, "EQUAL", 3)], 1) conway_rules = [rule1, rule2, rule3, rule4] # Create world populatedWorld = World("Test", 2000, 2000, 2, conway_rules, { 0: " ", 1: "#" }, {}) populatedWorld.spawn_points(ConwayPatterns.r_pentomino((10, 10)), 1) print(populatedWorld.active_points) # Config frameDelay = .1 # Runtime Variables frameCount = 1 input() while True: