def test_States_Is_Element_Valid(cls): current_states = States() file_path = 'pda.def' # Write the test case number cls.file.write(' ' + str(cls.test_case_number + 2) + '\t\t\t') current_states.load(file_path) # Write the Input cls.file.write('s1\t\t\t\t\t') # Write the Expected Output cls.file.write('True\t\t\t\t') try: cls.assertTrue(current_states.is_element('s1')) # Write the results cls.file.write('Passed\n') except AssertionError: #Write the results cls.file.write('Failed\n') # Increment test case number cls.test_case_number += 1
def test_States_Load(cls): current_states = States() file_path = 'pda.def' # Write the test case number cls.file.write(' ' + str(cls.test_case_number + 3) + '\t\t\t') current_states.load(file_path) # Write the Input cls.file.write(str(current_states.states) + '\t') # Write the Expected Output cls.file.write(str(current_states.states) + '\t') try: assert current_states.states == ['s0', 's1', 's2'] # Write the results cls.file.write('Passed\n') except AssertionError: #Write the results cls.file.write('Failed\n') # Increment test case number cls.test_case_number += 1
def test_States_Display_States(cls): current_states = States() file_path = 'pda.def' # Write the test case number cls.file.write(' ' + str(cls.test_case_number) + '\t\t\t') current_states.load(file_path) # Write the Input cls.file.write(str(current_states.states) + '\t') # Write the Expected Output cls.file.write('STATES: s0 s1 s2\t') display = current_states.view() try: cls.assertEqual(display, 'STATES: s0 s1 s2') # Write the results cls.file.write('Passed\n') except AssertionError: #Write the results cls.file.write('Failed\n') # Increment test case number cls.test_case_number += 1
def main(): b = Builder(4, 4, 1) goal = States(0, 0, 0, []) root = b.build_tree() # print(RenderTree(root)) print("Number of shortest path from ", root.name, " to ", goal.get_situation(), " is: ", search(root, goal))
def __init__(self): self.Input_Alpha = Input_Alphabet() self.Stack_Alpha = Stack_Alphabet() self.States = States() self.Final_States = Final_States() self.Transition = transition() self.operating = False #Add Transition_Function here file_path = '' description = '' initial_state = '' start_character = ''
def build(self, root, path): situation = root.name x = int(situation[0:1]) y = int(situation[2:3]) b = int(situation[4:]) state = States(x, y, b, path) children = self.get_state_children(state) for child in children: #child_state = States(child[0], child[1], child[2], state.get_path()) c = Node(str(child[0]) + "M" + str(child[1]) + "C" + str(child[2]), parent=root) self.build(c, state.get_path()) return root
def do_POST(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', 'text/html') self.end_headers() self.data_string = self.rfile.read(int(self.headers['Content-Length'])) # Analyze parameters if self.path.find('?') > -1: pathParams = self.path.split("?")[1] paramDic = self.CreateParamDic(pathParams) data = simplejson.loads(self.data_string) client_ip = self.getUrl(paramDic) message = data['message'] answer = "" if USERS_PREV_STATE[client_ip] == USERS[ client_ip] and not States.is_edge_state( USERS[client_ip].CURRENT_STATE): CONVERSATION_STUCK[client_ip] += 1 else: CONVERSATION_STUCK[client_ip] = 0 print("Stuck Times: " + str(CONVERSATION_STUCK[client_ip])) print(message) if len(message) > 0: user_message = User.UserMessage(USERS[client_ip], message) answer += hebChatbot.Start(user_message) else: # No message. Blocked in client side but who knows answer = "?" # Check if user is stuck and reset his conversation if CONVERSATION_STUCK[client_ip] >= 2 and not States.is_edge_state( USERS[client_ip].CURRENT_STATE): # Checking third mistake if USERS_PREV_STATE[client_ip] == USERS[client_ip]: # Reset chat message = ResetUserChat user_message = User.UserMessage(USERS[client_ip], message) answer = "לא הצלחתי להבין אותך, אני ממליץ לפנות טלפונית ל-012 שלוחה 3.\n" answer += hebChatbot.Start(user_message) CONVERSATION_STUCK[client_ip] = 0 self.wfile.write(bytes(answer, "utf-8")) # self.wfile.write(answer.encode("utf-8")) USERS_PREV_STATE[client_ip].make_equal(USERS[client_ip])
def main(): b = Builder(6, 6, 1) goal = States(0, 0, 0, []) root = b.build_tree() #print(RenderTree(root)) path, path_weight = a_star(root, goal) print("Shortest path: ", path, "\nPath Weight: ", path_weight)
def __init__(self, id): self.id = id from States import States self._addObject(States('states')) from Transitions import Transitions self._addObject(Transitions('transitions')) from Variables import Variables self._addObject(Variables('variables')) from Worklists import Worklists self._addObject(Worklists('worklists')) from Scripts import Scripts self._addObject(Scripts('scripts'))
def compare_features_to_outputs(): for k, v in States.items(): a1 = np.zeros(shape=(2, 1)) # dem party num a2 = np.zeros(shape=(2, 1)) # dem party money a3 = np.zeros(shape=(2, 1)) # dem cand num a4 = np.zeros(shape=(2, 1)) # dem cand money X = load_old_state_data(k) y = get_output_for_state(k) if X[0][0] > X[0][2]: a1[0] = 1 else: a1[0] = 2 if X[0][1] > X[0][3]: a2[0] = 1 else: a2[0] = 2 if X[0][6] > X[0][8]: a3[0] = 1 else: a3[0] = 2 if X[0][7] > X[0][9]: a4[0] = 1 else: a4[0] = 2 if X[1][0] > X[1][2]: a1[1] = 1 else: a1[1] = 2 if X[1][1] > X[1][3]: a2[1] = 1 else: a2[1] = 2 if X[1][6] > X[1][8]: a3[1] = 1 else: a3[1] = 2 if X[1][7] > X[1][9]: a4[1] = 1 else: a4[1] = 2 print(k) print(a1) print(a2) print(a3) print(a4) print(y)
def __init__(self, env_params, sim_params, scenario, simulator='traci'): super().__init__(env_params, sim_params, scenario, simulator) self.beta = env_params.get_additional_param("beta") self.tl_constraint_min = env_params.get_additional_param( "tl_constraint_min") self.tl_constraint_max = env_params.get_additional_param( "tl_constraint_max") self.action_spec = env_params.get_additional_param("action_spec") self.algorithm = env_params.get_additional_param("algorithm") self.sim_step = env_params.get_additional_param("sim_step") self.model_params = dict(beta=self.beta, ) self.rewards = Rewards(self.k, self.action_spec) self.states = States(self.k, self.beta) self._init_obs_veh_acc() self._init_obs_veh_wait_steps() self._init_obs_tl_wait_steps() # Used for debug purposes self.current_timestep = 0
import utils, os, json, csv from States import States conversionTestCases = [("129063.0", 129063), ('[7,331]', 7331), ('', -1), ('Unopposed', 0)] states = States() def testValueWithin(value, lower, higher): return value >= lower and value <= higher # Tests for converting string to int values for election dates. for case in conversionTestCases: assert utils.castToInt(case[0]) == case[1], "failed on '" + case[0] + "'" # Tests for getting a district assert utils.getDistrict( "AL", "./tables/2010.csv", 1)['R'] == 129063, "problem with rep count for AL 2010 dist 1:" + str( utils.getDistrict("AL", "./tables/2010.csv", 1)) assert utils.getDistrict("AZ", "./tables/2010.csv", 1)['D'] == 99233, "problem with dem count" assert utils.getDistrict("AZ", "./tables/2010.csv", 101) == {}, "problem with edge cases" assert utils.getDistrict("AZ", "./tables/2002.csv", 2)['R'] == 100359.0, "problem reading from 2002" assert utils.getDistrict("AL", "./tables/2000.csv", 2)['D'] == 64958.0, "problem reading from 2000"
break q += self.expand(path) visited.append(path) self.dfs([], 0, visited) print("Processing Test Data") ######################################################################## # # # Test Data # # # ######################################################################## yard = Yard([(1, 2), (1, 3), (3, 5), (4, 5), (2, 6), (5, 6)]) start = States([['*'], ['e'], [], ['b', 'c', 'a'], [], ['d']]) end = States([['*', 'a', 'b', 'c', 'd', 'e'], [], [], [], [], []]) switch = Switch(yard, start, end) yard2 = Yard([(1, 5), (1, 2), (2, 3), (2, 4)]) start2 = States([['*'], ['d'], ['b'], ['a', 'e'], ['c']]) end2 = States([['*', 'a', 'b', 'c', 'd', 'e'], [], [], [], []]) switch2 = Switch(yard2, start2, end2) yard3 = Yard([(1, 2), (1, 3)]) start3 = States([['*'], ['a'], ['b']]) end3 = States([['*', 'a', 'b'], [], []]) switch3 = Switch(yard3, start3, end3) yard4 = Yard([(1, 2), (1, 3), (1, 4)]) start4 = States([['*'], ['a'], ['b', 'c'], ['d']])
# get old data train_X = get_features('state_features.dat') train_y = get_all_outputs(States) # get new data test_X = get_features('new_state_features.dat') # get ml algorithm clf = DecisionTreeClassifier() #clf = LinearSVC() # fit ml algorithm with old data clf.fit(train_X, train_y) # predict each state for i, state in enumerate(sorted(States.items())): abbrev = state[0] data = state[1] votes = data['votes'] p = clf.predict(test_X[i]) if p == 1: clinton += votes else: trump += votes total += votes prediction[abbrev] = p print("Clinton: %d" % clinton)
class Automaton: def __init__(self): self.Input_Alpha = Input_Alphabet() self.Stack_Alpha = Stack_Alphabet() self.States = States() self.Final_States = Final_States() self.Transition = transition() self.operating = False #Add Transition_Function here file_path = '' description = '' initial_state = '' start_character = '' def load(self, path): file_path = path description = parse_file(path, '', 'STATES:') self.States.load(path) self.Input_Alpha.load(path) self.Stack_Alpha.load(path) self.initial_state = parse_file(path, 'INITIAL_STATE:', 'START_CHARACTER:') self.start_character = parse_file(path, 'START_CHARACTER:', 'FINAL_STATES:') self.current_state = self.initial_state[0] self.stack = self.start_character[0] self.transitions_list = [] self.next_symbol = self.stack self.Final_States.load(path) def run_string(self, string): self.operating = True self.string = string processed_string = '' for i in self.string: processed_string += i #Keeps track of how much of the string has been processed next_transition = self.run_through(i) self.transitions_list.append(next_transition) if len(next_transition) > 0: self.current_state = next_transition[0][0] self.stack = next_transition[0][1] + self.stack self.next_symbol = self.stack[0:1] if processed_string != self.string: #If the entire string has been processed then DON'T consume the top of the stack. self.stack = self.stack[1:] else: print('Could not process string') #return next_transition def run_through(self, char): next_transition = self.Transition.run(self.current_state, char, self.next_symbol) print(next_transition) return next_transition #if __name__ == "__main__": # aut = Automaton() # aut.load('pda.def') # aut.run_string('bbaaaaab')
def file_is_valid(self, file_path): self.Input_Alpha = Input_Alphabet() self.Input_Alpha.load(file_path) self.Stack_Alpha = Stack_Alphabet() self.Stack_Alpha.load(file_path) self.States = States() self.States.load(file_path) self.Final_States = Final_States() self.Final_States.load(file_path) self.transitions = parse_file(file_path, 'TRANSITION_FUNCTION:', 'INITIAL_STATE:') self.initial_state = parse_file(file_path, 'INITIAL_STATE:', 'START_CHARACTER:') self.start_character = parse_file(file_path, 'START_CHARACTER:', 'FINAL_STATES:') ### CHECK STATES KEYWORD CONTENT ### # Check if each element of STATES is not in INPUT ALPHABET, STACK ALPHABET, # or is the reserved character \ if not self.States.states: self.def_valid = False self.error_list.append('NO STATES FOUND!\n') for state in self.States.states: for letter in state: if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append('In STATES: ' + state + ' contains reserved character\n') elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In STATES: ' + state + ' cannot contain INPUT_ALPHABET characters\n') elif (self.Stack_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In STATES: ' + state + ' cannot contain STACK_ALPHABET characters\n') ### CHECK INPUT ALPHABET KEYWORD CONTENT ### # Check if each element of INPUT_ALPHABET is not the reserved character \, [ or ] self.seen = [] if not self.Input_Alpha.alphabet: self.def_valid = False self.error_list.append('NO INPUT ALPHABET CHARACTERS FOUND!\n') for alphabet in self.Input_Alpha.alphabet: for letter in alphabet: if (letter not in self.seen): self.seen.append(letter) else: self.def_valid = False self.error_list.append('In INPUT_ALPHABET: ' + letter + ' is specified twice\n') if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append('In INPUT_ALPHABET: ' + letter + ' contains reserved character\n') #elif (self.Stack_Alpha.is_element(letter) == True): # self.def_valid = False # self.error_list.append('In INPUT_ALPHABET: ' + letter + ' cannot be in both STACK_ALPHABET and INPUT_ALPHABET\n') ### CHECK STACK ALPHABET KEYWORD CONTENT ### # Check if each element of STACK_ALPHABET is not the reserved character \, [ or ] self.seen = [] if not self.Stack_Alpha.stack_alphabet: self.def_valid = False self.error_list.append('NO STACK ALPHABET CHARACTERS FOUND!\n') for alphabet in self.Stack_Alpha.stack_alphabet: for letter in alphabet: if (letter not in self.seen): self.seen.append(letter) else: self.def_valid = False self.error_list.append('In STACK_ALPHABET: ' + letter + ' is specified twice\n') if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append('In STACK_ALPHABET: ' + letter + ' contains reserved character\n') #elif (self.Input_Alpha.is_element(letter) == True): # self.def_valid = False # self.error_list.append('In STACK_ALPHABET: ' + letter + ' cannot be in both INPUT_ALPHABET and STACK_ALPHABET\n') ### CHECK TRANSITION FUNCTION KEYWORD CONTENT ### # Check if the transitions is not empty if not self.transitions: self.def_valid = False self.error_list.append('NO TRANSITIONS FOUND!\n') # While the transition list is not empty while (len(self.transitions) > 0): # Get a transition transition = self.transitions[0:5] # Delete the transition extracted from the transitions list del self.transitions[0:5] ### CHECK SOURCE STATE ### # Check if the source state is a valid state if (self.States.is_element(transition[0]) == False): self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + transition[0] + ' is not a valid source state\n') # Check if each element of source state is not in INPUT ALPHABET, STACK ALPHABET, # or is the reserved characters else: for letter in transition[0]: if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[0] + ' cannot contain reserved character\n') elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[0] + ' cannot contain INPUT_ALPHABET characters\n') elif (self.Stack_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[0] + ' cannot contain STACK_ALPHABET characters\n') ### CHECK READ CHARACTER ### # Check if the read character is a valid input alphabet if (len(transition[1]) != 1): self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + transition[1] + ' is not a valid read character\n') elif (self.Input_Alpha.is_element(transition[1]) == False): if (transition[1] == '\\'): # Reserved character \ is allowed in a transition # The pass needs to stay DO NOT DELETE IT pass elif (transition[1] == '[' or transition[1] == ']'): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[1] + ' cannot contain reserved character\n') else: self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + transition[1] + ' is not a valid read character\n') ### CHECK TOP OF STACK CHARACTER ### # Check if the top of stack character is a valid stack character if (len(transition[2]) != 1): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[2] + ' is not a valid top of stack character\n') elif (transition[2] == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + transition[2] + ' cannot contain reserved character\n') elif (self.Stack_Alpha.is_element(transition[2]) == False): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[2] + ' is not a valid top of stack character\n') ### CHECK DESTINATION STATE ### # Check if the destination state is a valid state if (self.States.is_element(transition[3]) == False): self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + transition[3] + ' is not a valid destination state\n') else: for letter in transition[3]: if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[3] + ' cannot contain reserved character\n') elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[3] + ' cannot contain INPUT_ALPHABET characters\n') elif (self.Stack_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + transition[3] + ' cannot contain STACK_ALPHABET characters\n') ### CHECK WRITE TO STACK CHARACTERS ### # Check if the write to stack characters are valid for letter in transition[4]: if (letter == '\\' and len(transition[4]) == 1): # Reserved character allowed in a transition # The pass needs to stay DO NOT DELETE IT pass elif (letter == '\\' and len(transition[4]) > 1): self.def_valid = False self.error_list.append('In Transition: \n' + ' '.join(transition) + ' \n' + letter + ' needs to be only character\n') elif (letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + letter + ' cannot contain reserved character\n') elif (self.Stack_Alpha.is_element(letter) == False): self.def_valid = False self.error_list.append( 'In Transition: \n' + ' '.join(transition) + ' \n' + letter + ' is not a valid write to stack character\n') ### CHECK INITIAL STATE KEYWORD CONTENT ### # Check if there are multiple start states if not self.initial_state: self.def_valid = False self.error_list.append('NO INITIAL STATE FOUND!\n') if (len(self.initial_state) != 1): self.def_valid = False self.error_list.append( 'In INITIAL_STATES: Only one initial state permitted\n') # Check if the start state is a element of the set of states elif (self.States.is_element(self.initial_state[0]) == False): self.def_valid = False self.error_list.append('In INITIAL_STATE: ' + self.initial_state[0] + ' is not in the set of STATES\n') # Check that the initial state does not contains INPUT_ALPHABET, STACK_ALPHABET, or reserved character else: for state in self.initial_state: for letter in state: if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In INITIAL_STATES: ' + state + ' cannot contain reserved character\n') elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In INITIAL_STATES: ' + state + ' cannot contain INPUT_ALPHABET characters\n') elif (self.Stack_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In INITIAL_STATES: ' + state + ' cannot contain STACK_ALPHABET characters\n') ### CHECK START CHARACTER KEYWORD CONTENT ### # Check if there are multiple start characters if not self.start_character: self.def_valid = False self.error_list.append('NO START CHARACTER FOUND!\n') if (len(self.start_character) != 1): self.def_valid = False self.error_list.append( 'In STATE_CHARACTER: Only one start character permitted\n') # Check if the start character is a element of the set of stack characters elif (self.Stack_Alpha.is_element(self.start_character[0]) == False): self.def_valid = False self.error_list.append('In START_CHARACTER: ' + self.start_character[0] + ' is not in stack alphabet\n') # Check that the start character does not contain the INPUT_ALPHABET and reserved character else: for alphabet in self.start_character: for letter in alphabet: if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In START_CHARACTER: ' + alphabet + ' cannot contain reserved character\n') elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In START_CHARACTER: ' + alphabet + ' cannot contain INPUT_ALPHABET characters\n') ### CHECK FINAL STATES KEYWORD CONTENT ### # Check if each final state is valid if not self.Final_States.final_states: self.def_valid = False self.error_list.append('NO FINAL STATES FOUND!\n') for state in self.Final_States.final_states: # Check if each final state is an element of states if (self.States.is_element(state) == False): self.def_valid = False self.error_list.append('In FINAL_STATES: ' + state + ' is not in the set of STATES\n') for letter in state: # Check for reserved character if (letter == '\\' or letter == '[' or letter == ']'): self.def_valid = False self.error_list.append( 'In FINAL_STATES: ' + state + ' cannot contain reserved character\n') # Check for input alphbet character elif (self.Input_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In FINAL_STATES: ' + state + ' cannot contain INPUT_ALPHABET characters\n') # Check for stack alphabet elif (self.Stack_Alpha.is_element(letter) == True): self.def_valid = False self.error_list.append( 'In FINAL_STATES: ' + state + ' cannot contain STACK_ALPHABET characters\n')
def do_POST(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', 'text/html') self.end_headers() self.data_string = self.rfile.read(int(self.headers['Content-Length'])) # Analyze parameters if self.path.find('?') > -1: pathParams = self.path.split("?")[1] paramDic = self.CreateParamDic(pathParams) data = simplejson.loads(self.data_string) client_ip = self.getUrl(paramDic) message = data['message'] self.answer = "" if USERS_PREV_STATE[client_ip] == USERS[ client_ip] and not States.is_edge_state( USERS[client_ip].CURRENT_STATE): CONVERSATION_STUCK[client_ip] += 1 else: CONVERSATION_STUCK[client_ip] = 0 print("Stuck Times: " + str(CONVERSATION_STUCK[client_ip])) print(message) if len(message) > 0: global test_checker global schedule_checker user_message = User.UserMessage(USERS[client_ip], message) self.answer += hebChatbot.Start(user_message) if test_checker is False and schedule_checker is True: tests_urls = self.return_json_file('test.json') option_1 = Options_to_classes.option(1) option_2 = Options_to_classes.option(2) option_3 = Options_to_classes.option(3) array_keys = [] for key in tests_urls.items(): array_keys.append(key[0]) if message in tests_urls: self.answer = self.return_tests(message, tests_urls) self.answer += "\r\n" + "אוכל לעזור בעוד משהו ?" elif message in option_1: index = option_1.index(message) message = array_keys[index] self.answer = self.return_tests(message, tests_urls) self.answer += "\r\n" + "אוכל לעזור בעוד משהו ?" elif message in option_2: index = option_2.index(message) message = array_keys[index] tests = self.return_tests(message, tests_urls) self.answer = tests self.answer += "\r\n" + "אוכל לעזור בעוד משהו ?" elif message in option_3: index = option_3.index(message) message = array_keys[index] tests = self.return_tests(message, tests_urls) self.answer = tests self.answer += "\r\n" + "אוכל לעזור בעוד משהו ?" else: self.answer = "?" user_message = User.UserMessage(USERS[client_ip], message) self.answer += hebChatbot.Start(user_message) test_checker = True if schedule_checker is False and test_checker is True: self.answer = "" schedule_payload = self.return_json_file('schedule_payload') schedule_con_type = self.return_json_file('schedule_con_type') (payload, con_type) = self.return_schedule(message, schedule_payload, schedule_con_type) if payload is not False: schedule_checker = True day_1 = [] day_2 = [] day_3 = [] day_4 = [] day_5 = [] day_6 = [] url = URL_FOR_SCHEDULE headers = {'content-type': con_type} response = requests.request("POST", url, data=payload, headers=headers) result = self.find_between(response.text, SCHEDULE_START, SCHEDULE_END) nowdays = re.findall('<td class(.*)', result)[0:6] for num, item in enumerate(nowdays): nowdays[num] = nowdays[num].replace("</td>\r", "") nowdays[num] = nowdays[num].replace( """="CTitle">""", "") a = re.findall('<table width(.*)', result) b = a[0] a.remove(b) for num, item in enumerate(a): item = item.replace( """=\\'100%\\'><tr><td class=\\'TableExamChange\\'>""", """=\\'100%\\'></table><div class="TTLesson"><b>""" ) item = item.replace("</td></tr></table>", "</div>") item = item.replace("<br />", " ") item = item[41:] item = item.replace("</b><br>", "--") item = item.replace( """</div><div class="TTLesson"><b>""", " ") item = item.replace("</b> ", "") item = item.replace("<br>", " עם ") item = item[:-7] item = item.replace("בחן", "מבחן") item = item.replace("יטול", "ביטול") print(num, item) if num % 6 == 0: day_1.append(item) elif num % 6 == 1: day_2.append(item) elif num % 6 == 2: day_3.append(item) elif num % 6 == 3: day_4.append(item) elif num % 6 == 4: day_5.append(item) elif num % 6 == 5: day_6.append(item) self.loop_for_schedule(day_1, nowdays, 0) self.loop_for_schedule(day_2, nowdays, 1) self.loop_for_schedule(day_3, nowdays, 2) self.loop_for_schedule(day_4, nowdays, 3) self.loop_for_schedule(day_5, nowdays, 4) self.loop_for_schedule(day_6, nowdays, 5) self.answer += "\r\n" + "אוכל לעזור בעוד משהו ?" else: self.answer = "?" user_message = User.UserMessage(USERS[client_ip], message) self.answer += hebChatbot.Start(user_message) if "לוח מבחנים" in message: self.answer = "איזה כיתה את\ה ?" test_checker = False elif "מערכת שעות" in message: self.answer = "איזה כיתה את\ה ?" schedule_checker = False else: # No message. Blocked in client side but who knows self.answer = "?" user_message = User.UserMessage(USERS[client_ip], message) self.answer += hebChatbot.Start(user_message) if CONVERSATION_STUCK[client_ip] >= 2 and not States.is_edge_state( USERS[client_ip].CURRENT_STATE): # Checking third mistake if USERS_PREV_STATE[client_ip] == USERS[client_ip]: # Reset chat message = ResetUserChat user_message = User.UserMessage(USERS[client_ip], message) answer = "לא הצלחתי להבין אותך, אני ממליץ לפנות טלפונית ל-012 שלוחה 3.\n" answer += hebChatbot.Start(user_message) CONVERSATION_STUCK[client_ip] = 0 self.wfile.write(bytes(self.answer, "utf-8")) # self.wfile.write(answer.encode("utf-8")) USERS_PREV_STATE[client_ip].make_equal(USERS[client_ip])
def do_POST(self): # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', 'text/html') self.end_headers() self.data_string = self.rfile.read(int(self.headers['Content-Length'])) # Analyze parameters if self.path.find('?') > -1: pathParams = self.path.split("?")[1] paramDic = self.CreateParamDic(pathParams) data = simplejson.loads(self.data_string) client_ip = self.getUrl(paramDic) message = data['message'] self.answer = "" if USERS_PREV_STATE[client_ip] == USERS[client_ip] and not States.is_edge_state(USERS[client_ip].CURRENT_STATE): CONVERSATION_STUCK[client_ip] += 1 else: CONVERSATION_STUCK[client_ip] = 0 print("Stuck Times: " + str(CONVERSATION_STUCK[client_ip])) print(message) if len(message) > 0: global checker user_message = User.UserMessage(USERS[client_ip], message) self.answer += hebChatbot.Start(user_message) print(checker) if checker is False: with open('test.json', 'rb') as f: tests_urls = f.read() tests_urls = json.loads(tests_urls) option_1 = Options_to_classes.option(1) option_2 = Options_to_classes.option(2) if message in tests_urls: tests = self.return_tests(message, tests_urls) self.answer = tests elif message in option_1: index = option_1.index(message) array_keys = [] for key in tests_urls.items(): array_keys.append(key[0]) message = array_keys[index] tests = self.return_tests(message, tests_urls) self.answer = tests elif message in option_2: index = option_2.index(message) array_keys = [] for key in tests_urls.items(): array_keys.append(key[0]) message = array_keys[index] tests = self.return_tests(message, tests_urls) self.answer = tests checker = True if "לוח מבחנים" in message: self.answer = "איזה כיתה את\ה ?" checker = False else:# No message. Blocked in client side but who knows self.answer = "?" # Check if user is stuck and reset his conversation if CONVERSATION_STUCK[client_ip] >= 2 and not States.is_edge_state(USERS[client_ip].CURRENT_STATE): # Checking third mistake if USERS_PREV_STATE[client_ip] == USERS[client_ip]: # Reset chat message = ResetUserChat user_message = User.UserMessage(USERS[client_ip], message) self.answer = "לא הצלחתי להבין אותך, אנא פנה לאתר של בליך\n" self.answer += hebChatbot.Start(user_message) CONVERSATION_STUCK[client_ip] = 0 self.wfile.write(bytes(self.answer, "utf-8")) # self.wfile.write(self.answer.encode("utf-8")) USERS_PREV_STATE[client_ip].make_equal(USERS[client_ip])
def __init__(self, x, y, b): self.root = Node(str(x) + "M" + str(y) + "C" + str(b)) self.root_state = States(x, y, b, [])