def do_controller_specific_work(self): phonenumber_regex = re.compile(r"\d{10}") result = phonenumber_regex.match(self.phonenumber) if result is None: raise API_Exception(400, "Invalid phone number") else: db_session = DB_Session_Factory.get_db_session() cfg = CFG.get_instance() if self.phonenumber != str(cfg.get('apple_tester', 'phone_number')): user = db_session.query(User).get(self.phonenumber) current_ts = datetime.now() if user is None: user = User() user.phonenumber = self.phonenumber user.device_vendor_id = self.device_vendor_id user.access_token = None user.confirmation_token = self.generate_confirmation_token() user.confirmation_deadline = current_ts + timedelta(minutes = 5) user.last_request_ts = current_ts db_session.add(user) db_session.commit() else: user.confirmation_token = self.generate_confirmation_token() user.confirmation_deadline = current_ts + timedelta(minutes = 5) user.last_request_ts = current_ts db_session.add(user) db_session.commit() message = "Your code is " + user.confirmation_token self.send_code_to_phone(code_message=message, to_number=user.phonenumber) return HTTP_Response('200 OK', {'status' : 'SMS request sent'})
def do_controller_specific_work(self): cfg = CFG.get_instance() targets_for_signup = int(cfg.get('sales_pitch', 'targets_for_signup')) # if you're chaning number of free classes in auth pitch, also change sales_pitch and user/update.py auth_pitch = 'Please register with Class Radar to start tracking classes you are interested in.' auth_pitch = auth_pitch + ' You can target ' + str(targets_for_signup) + ' classes for free after you register.' auth_pitch = auth_pitch + ' We don\'t use your phone number for anything other than keeping track of your targets.' return HTTP_Response('200 OK', {'auth_pitch' : auth_pitch})
def do_controller_specific_work(self): phonenumber_regex = re.compile(r"\d{10}") confirmation_token_regex = re.compile(r"\d{6}") phonenumber = self.resource_id result = phonenumber_regex.match(phonenumber) if result is None: raise API_Exception(400, "Invalid phone number") return result = confirmation_token_regex.match(self.confirmation_token) if result is None: raise API_Exception(400, "Invalid confirmation token") return db_session = DB_Session_Factory.get_db_session() user = db_session.query(User).get(self.resource_id) if user is None: raise API_Exception(404, "Entry does not exist in DB") return current_ts = datetime.now() if (current_ts > user.confirmation_deadline): raise API_Exception(403, "Confirmation token request came exceeded confirmation deadline. Request next confirmation token") return if (user.confirmation_token != self.confirmation_token): raise API_Exception(401, "Wrong confirmation token") return # if all of above checks passed we have a valid phone number, confirmation token and confirmation done within # appropriate confirmation deadline. Go ahead, generate authorization token and give it back to user user.last_request_ts = current_ts # if user registers phone for the first time, generate token # and create credits if user.access_token is None: user.access_token = self.generate_access_token() userProfile = db_session.query(UserProfile).get(self.resource_id) if userProfile is None: userProfile = UserProfile() userProfile.phonenumber = user.phonenumber userProfile.didPostOnFb = False userProfile.didPostOnTwitter = False userProfile.referred_by = self.referred_by cfg = CFG.get_instance() userProfile.credits = int(cfg.get('sales_pitch', 'targets_for_signup')) userProfile.email = None db_session.add(userProfile) db_session.commit() return HTTP_Response('200 OK', {'access_token' : user.access_token})
def bin(cfg: CFG, show_steps: bool) -> CFG: variables = cfg.get_variables() new_productions = Productions() for head, tail in cfg.get_productions().items(): i = 0 while i < len(tail): if len(tail[i]) <= 2: if show_steps: print(f"{head} -> {tail[i]} is already valid") new_productions.add_production(head, tail[i]) i += 1 continue if show_steps: print(f"{head} -> {tail[i]} is too large") new_head = head # When this loop finishes there will be 2 # variables (or terminals) left j = 0 while j < len(tail[i]) - 2: # Find a new variable that already isn't in variables new_var = gen_new_variabele(variables) new_tail = tail[i][j] + new_var if show_steps: print( f"Creating a new production {new_head} -> {new_tail}") new_productions.add_production(new_head, new_tail) variables.add(new_var) # Set the new variable to the old variable new_head = new_var j += 1 # Get last two variables (or terminals) from the tail new_tail = tail[i][j] + tail[i][j + 1] if show_steps: print(f"Creating the last production {new_var} -> {new_tail}") new_productions.add_production(new_var, new_tail) i += 1 return CFG(cfg.get_start_state(), new_productions)
def term(cfg: CFG, show_steps: bool) -> CFG: productions = cfg.get_productions() variables = cfg.get_variables() new_productions = Productions() for head, tails in productions.items(): for tail in tails: if len(tail) < 2 or not any([char in productions for char in tail]): new_productions.add_production(head, tail) continue terminals = {char for char in tail if char not in productions} new_tail = tail for terminal in terminals: # Get new variable new_var = gen_new_variabele(variables) # Add nwe variable new_productions.add_production(new_var, terminal) variables.add(new_var) # Replace the terminal in the tail with a variable new_tail = new_tail.replace(terminal, new_var) # Finally add the new tail new_productions.add_production(head, new_tail) return CFG(cfg.get_start_state(), new_productions)
def convert_to_chomsky(cfg: CFG, show_steps=False) -> CFG: prod = cfg.get_productions() prod.add_production("P", cfg.get_start_state()) new = CFG("P'", prod) a = bin(cfg, show_steps) print("== Done with bin ==") print(a) print("===================") b = dell(a, show_steps) print("== Done with del ==") print(b) print("===================") c = unit(b, show_steps) print("== Done with unit ==") print(c) print("====================") d = term(c, show_steps) print("== Done with term ==") print(d) print("====================")
def parse_cfg_string(string: str) -> CFG: # Can not contain productions like # A -> b # A -> c # It has to be in the form # A -> b | c start = None productions = Productions() for line in string.split("\n"): l1 = line.split("->") head = l1[0].strip() for l in l1[1].split("|"): productions.add_production(head, l.strip()) if start is None: start = head assert start is not None return CFG(start, productions)
def dell(cfg: CFG, show_steps: bool) -> CFG: new_cfg = CFG(cfg.get_start_state(), cfg.get_productions()) # Set of nullable variables nullables = set() # Find all variables that are nullable in one step for head, tails in cfg.get_productions().items(): for tail in tails: if tail == "!": if show_steps: print(f"{head} -> {tail} is a nullable symbol") nullables.add(head) for nullable in nullables: new_cfg.remove_production(nullable, "!") for head, tails in new_cfg.get_dict_productions_raw().items(): new_tails = tails.copy() for tail in tails: # Check if tail contains nullable symbol if tail.count(nullable) > 0: if show_steps: print(f"{head} -> {tail} contains nullabe symbols") # Find all indexes indexes = [m.start() for m in re.finditer(nullable, tail)] # Get all combinations for L in range(1, len(indexes) + 1): for subset in itertools.combinations(indexes, L): listy = list(subset) listy.sort() new_tail = tail for i, pos in enumerate(listy): new_tail = new_tail[:pos - i] + new_tail[pos - i + 1:] if show_steps: print(f"Adding {head} -> {new_tail}") new_tails.append(new_tail) # Add the new tails found for new_tail in set(new_tails).difference(tails): tails.append(new_tail) return new_cfg
def do_controller_specific_work(self): if self.user is None: raise Authorization_Exception("You must be logged in to perform IAP.") db_session = DB_Session_Factory.get_db_session() user_profile = db_session.query(UserProfile).get(self.user.phonenumber) if user_profile is None: raise API_Exception(500, "User profile does not exist") # This throws if the check fails. self.checkVerificationService() # The check succeeded. Let's give a lot of credits to user profile. cfg = CFG.get_instance() targets_for_purchase = int(cfg.get('sales_pitch', 'targets_for_purchase')) user_profile.credits += targets_for_purchase db_session.commit() return HTTP_Response('200 OK', {'credits' : user_profile.credits})
def parse_cfg(path: str) -> CFG: with open(path) as f: lines = f.read().splitlines() # Can not contain productions like # A -> b # A -> c # It has to be in the form # A -> b | c start = None productions = Productions() for line in lines: l1 = line.split("->") head = l1[0].strip() for l in l1[1].split("|"): productions.add_production(head, l.strip()) if start is None: start = head assert start is not None return CFG(start, productions)
def get_db_session(debug=False): if DB_Session_Factory.Session is None: db_engine = create_engine(CFG.get_instance().get('db', 'dsn'), echo=debug, poolclass=QueuePool, pool_size = 5, pool_recycle = 3600, pool_reset_on_return = 'rollback', pool_timeout = 30, encoding = 'utf-8') DB_Session_Factory.Session = scoped_session(sessionmaker(bind = db_engine)) session = DB_Session_Factory.Session() return session
def send_code_to_phone(self, code_message, to_number): cfg = CFG.get_instance() client = TwilioRestClient(cfg.get('twilio', 'account'), cfg.get('twilio', 'auth_token')) client.sms.messages.create(to=to_number,from_=cfg.get('twilio', 'from_phone'),body=code_message)
def unit(cfg: CFG, show_steps: bool) -> CFG: productions = cfg.get_productions() new_cfg = CFG(cfg.get_start_state(), cfg.get_productions()) while True: # Find unit pairs unit_pairs = set() for head, tails in new_cfg.get_productions().items(): for tail in tails: if tail in productions: unit_pairs.add((head, tail)) # Break when can't find any more unit pairs if len(unit_pairs) == 0: break for pair in unit_pairs: head, tt = pair new_tails = [] # Remove the unit pair new_cfg.get_dict_productions_raw()[head].remove(tt) if show_steps: print(f"Removing unit pair {head} -> {tt}") for tail in new_cfg.get_dict_productions_raw()[tt]: new_tails.append(tail) for new_tail in new_tails: if show_steps: print( f"Adding {head} -> {new_tail} since we had that {tt} -> {new_tail}" ) new_cfg.add_production(head, new_tail) # new_cfg.remove_unreachable_productions() return new_cfg
def get_db_session(): if DB_Session_Factory.session is None: db_engine = create_engine(CFG.get_instance().get('db', 'dsn'), echo=False) Session = sessionmaker(bind = db_engine) DB_Session_Factory.session = Session() return DB_Session_Factory.session