def SearchAction(userId, phrase): if phrase: matchingActionsQuery = Action.query(Action.keywords.IN(SplitPhrase(phrase)), ancestor=GetAccountKey(userId)) else: matchingActionsQuery = Action.query(ancestor=GetAccountKey(userId)) return matchingActionsQuery.fetch()
def get_action_from_label(self, label, create_action_if_needed, project): action = Action.query(ancestor=project.key).filter(Action.label == label).get() if action == None and create_action_if_needed: # Create a temp store of actions created just for this run. if label not in self.__temp_actions: action = Action( parent=project.key, name=label, type="Response", label=label, x_axis=0, y_axis=0, y_axis_max="duration", ) action.put() self.__temp_actions[label] = action else: action = self.__temp_actions[label] return action
def sync_db(self, user_id, channel, category_type, category_offset): cur_time = utilities.get_time() categories = [i + " " + category_type for i in ["end", "start"]] cur_category = categories[category_offset] last_record = self.get_last_record(user_id, categories) # Heuristic data recovery if users have voice_state_update when the bot is down # See all possible scenarios in test_bot.py if last_record: # For case: # last: start id_1 # cur: end id_2 if last_record.detail != channel.id and categories.index( last_record.category): # Add end for last last_category_offset = categories.index(last_record.category) cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[1 - last_category_offset], detail=last_record.detail, creation_time=cur_time) self.sqlalchemy_session.add(record) if category_offset == 0: # Add start for cur # A bit inelegant when a user with video on switches to another channel cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[last_category_offset], detail=channel.id, creation_time=cur_time) self.sqlalchemy_session.add(record) # For case: # start(end) id_1 # start(end) id_1 # end id_1 # end id_2 elif last_record.category == cur_category: cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[1 - category_offset], detail=last_record.detail, creation_time=cur_time) self.sqlalchemy_session.add(record) cur_time += timedelta(microseconds=1) # Users might jump to non-monitored channels if check_categories(channel): record = Action(user_id=user_id, category=cur_category, detail=channel.id, creation_time=cur_time) self.sqlalchemy_session.add(record) utilities.commit_or_rollback(self.sqlalchemy_session) return last_record.creation_time if last_record else cur_time
def testInsertWithAccountKey(self): TEST_USER_ID = 'testUserId' accountKey = GetAccountKey(TEST_USER_ID) act = Action(parent=accountKey) act.keywords = ['a', 'b', 'c'] act.put() self.assertEquals(1, len(Action.query(ancestor=accountKey).fetch(2)))
def testFetchRedirectAttribute(self): TEST_LINK = 'test link' act = Action(redirect_link=TEST_LINK) act.put() self.assertEquals(1, len(Action.query().fetch(2))) fetched = Action.query().fetch(2)[0] self.assertEquals(TEST_LINK, fetched.redirect_link)
def testFetchKeywordsAttribute(self): TEST_KEY_WORDS = ['key', 'words', 'test'] act = Action(keywords=TEST_KEY_WORDS) act.put() self.assertEquals(1, len(Action.query().fetch(2))) fetched = Action.query().fetch(2)[0] for word in TEST_KEY_WORDS: self.assertTrue(word in fetched.keywords)
def genearate_states(self): initial = self.grammar.productions.get_augmented()[0] dotted_initial = self.add_dot(initial) state = [dotted_initial] for e in self.generate_additional_state_elements(production=dotted_initial): state.append(e) self.states.append(state) index = 0 # generate states while index < len(self.states): if index not in self.table.entries: self.table.entries[index] = self.prepare_table_entry() toadd = [] transitions = [] for pr in self.states[index]: goto = self.goto(pr) if len(goto) > 0: element_to_add = self.get_element_before_dot(goto[0]) transitions.append((element_to_add, goto)) if goto not in toadd: if goto not in self.states: toadd.append(goto) for gt in toadd: self.states.append(gt) for t in transitions: idx = self.states.index(t[1]) if idx not in self.table.entries: self.table.entries[idx] = self.prepare_table_entry() if t[1][0].rhs[-1].is_dot: p = Production(lhs=t[1][0].lhs, rhs=t[1][0].rhs[:-1]) if p == initial: self.table.entries[idx].action['$'] = Action(action='accept', number=None) else: for y in self.table.entries[idx].action: self.table.entries[idx].action[y] = Action(action='reduce', number=str(self.grammar.productions.productions.index(p) + 1)) if t[0].terminal: self.table.entries[index].action[t[0].name] = Action(action='shift', number=str(self.states.index(t[1]))) else: self.table.entries[index].goto[t[0].name] = Action(action='goto', number=str(self.states.index(t[1]))) index += 1 for i, state in enumerate(self.states): print(str(i) + ": " + ",".join(map(str, state))) for k, v in self.table.entries.items(): print(str(k) + ": " + str(v))
def action_put(request): dbsession = DBSession() action = Action() action.name = clean_matchdict_value(request, 'action') action.description = clean_param_value(request, 'description') action.points = clean_param_value(request, 'points') action.timestamp = get_timestamp() dbsession.add(action) transaction.commit() return {'status': 'success'}
def testInsertAction(self): TEST_USER_ID = 'testUserId' TEST_PHRASE = 'this is a test' TEST_LINK = 'https://www.google.com/shopping/express' InsertAction(TEST_USER_ID, TEST_PHRASE, TEST_LINK) accountKey = GetAccountKey(TEST_USER_ID) self.assertEquals(1, len(Action.query(ancestor=accountKey).fetch(2))) fetched = Action.query().fetch(2)[0] self.assertEquals(fetched.redirect_link, TEST_LINK)
def sync_db(self, user_id, channel, category_type, category_offset): cur_time = utilities.get_time() categories = [i + " " + category_type for i in ["end", "start"]] cur_category = categories[category_offset] last_record = self.get_last_record(user_id, categories) # data recovery if last_record: # For case: # last: start id_1 # cur: end id_2 if last_record.detail != channel.id and categories.index( last_record.category): # Add end for last last_category_offset = categories.index(last_record.category) cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[1 - last_category_offset], detail=last_record.detail, creation_time=cur_time) self.sqlalchemy_session.add(record) if category_offset == 0: # Add start for cur # A bit inelegant when a user with video on switches to another channel cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[last_category_offset], detail=channel.id, creation_time=cur_time) self.sqlalchemy_session.add(record) # For case: # start(end) id_1 # start(end) id_1 # end id_1 # end id_2 elif last_record.category == cur_category: cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=categories[1 - category_offset], detail=last_record.detail, creation_time=cur_time) self.sqlalchemy_session.add(record) cur_time += timedelta(microseconds=1) record = Action(user_id=user_id, category=cur_category, detail=channel.id, creation_time=cur_time) self.sqlalchemy_session.add(record) utilities.commit_or_rollback(self.sqlalchemy_session) return last_record.creation_time if last_record else cur_time
def act(actor, target, action, narration): acting_on_self = target.key().name() == actor.key().name() a = Thespian(actor) if acting_on_self: t = a else: t = Thespian(target) action_types[action].run_script(a, t) now = datetime.now() db.run_in_transaction(a.run_effects_at, now) if not acting_on_self: db.run_in_transaction(t.run_effects_at, now) Action.create(actor, target, now, action, narration, a.effect_summary(), t.effect_summary())
def post(self): form = SessionCreateForm() if not form.validate_on_submit(): return form.errors, 422 user = User.query.filter_by(email=form.email.data.lower()).first() tmp_pwd_hash = generate_password_hash(form.password.data) if user and check_password_hash(user.password, form.password.data): if datetime.datetime.now() > user.lastLoginDateTime + datetime.timedelta(minutes=ConfigManager.NODE_LOG_MERGE): logentry = Action(datetime.datetime.utcnow(), ConfigManager.NODE_NAME, user.firstName + ' ' + user.lastName, user.email, 'User login', 'User login', 'L2', 0, 'Web based') user.lastLoginDateTime = datetime.datetime.now() try: db.session.add(logentry) db.session.commit() except: raise return '', 201 print "Log-entry created" else: print "Log-entry is in merge-range ts = " + str(datetime.datetime.utcnow()) + " last = " + str(user.lastLoginDateTime) + " merge = " + str(ConfigManager.NODE_LOG_MERGE) + " minutes" return SessionInfoSerializer().dump(user).data, 201 else: lastlogEntry = Action.query.filter_by(logType='Failed login attempt', userMail=form.email.data).order_by(Action.date.desc()).first() addNewlogEntry = True if lastlogEntry is None: addNewlogEntry = True else: if datetime.datetime.utcnow() > (lastlogEntry.date + datetime.timedelta(minutes=30)): addNewlogEntry = True else: addNewlogEntry = False if addNewlogEntry == True: logentry = Action(datetime.datetime.utcnow(), ConfigManager.NODE_NAME, 'Security warning', form.email.data, 'Failed login for ' + form.email.data + ' ( 1 invalid attempts)', 'Failed login attempt', 'L1', 0, 'Internal', Action.ACTION_LOGONLY, 1) db.session.add(logentry) else: lastlogEntry.actionParameter += 1 lastlogEntry.logText = 'Failed login for ' + form.email.data + ' (' + str(lastlogEntry.actionParameter) + ' invalid attempts)' db.session.commit() return '', 401
def get_single_load_action_from_multi_label (self, project, labels): if not self.is_multi_label(labels): return None actions = Action.query(ancestor=project.key) load_action = None for action in actions: # Skip over any Actions that aren't in the set of labels. if action.name not in labels: continue if action.type == 'Load': # If we've just hit the first Load Action, set it, otherwise # unset it and break out of the loop. if load_action == None: load_action = action else: load_action = None break # Return either None or the only load action return load_action
def createAction(): action_name = "action_" + request.form['action_name'] actionObj = Action(name=action_name) conv_action_name = convertNameToCamel(action_name) code_content = ''' class %s(Action): def name(self) -> Text: return "%s" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: #use tracker.get_slot to retrieve slot values if they are set #foo = tracker.get_slot('your_slot_name') #use dispatcher.utter_message to return the message the chatbot should output dispatcher.utter_message("Hello World!") return [] ''' % (conv_action_name, action_name) f = open("actions.py", "a") f.write(code_content) f.close() db.session.add(actionObj) db.session.commit() return render_template( "success.html", message="Action created. Open actions.py to add custom code.")
def backup_cycle(self): lasttime = self.lastBackupTime now = datetime.datetime.now() compare_time = lasttime.replace(hour=4, minute=35, second=0, microsecond=0) if compare_time > lasttime: next_time = compare_time else: next_time = compare_time + datetime.timedelta(days=1) if now > next_time or self.forceBackup == True: self.forceBackup = False print 'Doing a backup (' + str(datetime.datetime.now()) + ')' with app.app_context(): flask_alchemydumps.autoclean(True) flask_alchemydumps.create() if config.BACKUP_ENABLE_FTP == True: print 'Doing a additional FTP backup' app.config['ALCHEMYDUMPS_FTP_SERVER'] = '' app.config['ALCHEMYDUMPS_FTP_USER'] = '' app.config['ALCHEMYDUMPS_FTP_PASSWORD'] = '' app.config['ALCHEMYDUMPS_FTP_PATH'] = '' flask_alchemydumps.create() app.config['ALCHEMYDUMPS_FTP_SERVER'] = config.ALCHEMYDUMPS_FTP_SERVER app.config['ALCHEMYDUMPS_FTP_USER'] = config.ALCHEMYDUMPS_FTP_USER app.config['ALCHEMYDUMPS_FTP_PASSWORD'] = config.ALCHEMYDUMPS_FTP_PASSWORD app.config['ALCHEMYDUMPS_FTP_PATH'] = config.ALCHEMYDUMPS_FTP_PATH print 'Next backup @' + str(next_time) + ' (' + str(datetime.datetime.now()) + ')' logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, 'Sync Master', '*****@*****.**', 'Backup database', 'Backup', 'L1', 0, 'Internal') db.session.add(logentry) db.session.commit() self.lastBackupTime = now
def create_file_action(path, action_id, session_id, project_id): """ Logs a file action to the database. :param path: Filepath. :type path: String :param action_id: File action id. :type action_id: Integer :param session_id: Current session id. :type session_id: Integer :param project_id: Project id from database. :type project_id: Integer """ args = (File.path == path, ) kwargs = {'path': path, 'project_id': project_id} if is_project_file(path, project_id): args = args + (File.project_id == project_id, ) file_object = controller.common.get_or_create(File, *args, **kwargs) action_object = Action.get_by_id(action_id) session_object = Session.get_by_id(session_id) if session_id > 0 else None return FileAction(file_object, action_object, session_object)
def get_single_load_action_from_multi_label(self, project, labels): if not self.is_multi_label(labels): return None actions = Action.query(ancestor=project.key) load_action = None for action in actions: # Skip over any Actions that aren't in the set of labels. if action.name not in labels: continue if action.type == 'Load': # If we've just hit the first Load Action, set it, otherwise # unset it and break out of the loop. if load_action == None: load_action = action else: load_action = None break # Return either None or the only load action return load_action
def api_invite_user(): email = request.args.get('email') token = str(uuid.uuid4()) user = User(email, token) db.session.add(user) current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='inviteuser', target_type='user', text='Invited user ({0})'.format( user.email), target_id=user.id) db.session.add(action) db.session.commit() try: send_email = request.args.get('send_email') except: return jsonify(status="OK") if send_email or send_email == 'true': url = url_for('login', token=token, _external=True) email_html = render_template( "email_vote.html", u_id=email, vote_url=url) text = "Hi there {0},\n\nPlease click on the link below to vote on {1}. This vote will close on {2}.\n\n{3}\n\n--{4}".format( email, app.config['VOTE_DESCRIPTION'], app.config['END_DATE_STR'], url, app.config['ORGANIZATION_NAME']) subject = app.config['ORGANIZATION_NAME'] + ": Please vote!" utils.mailgun_send_message(subject, [email], text, html=email_html) return jsonify(status="OK")
def cleanup_cycle(self): lasttime = self.lastCleanupTime now = datetime.datetime.now() past = now - datetime.timedelta(days=ConfigManager.CLEANUP_THRESHOLD) compare_time = lasttime.replace(hour=04, minute=55, second=0, microsecond=0) if compare_time > lasttime: next_time = compare_time else: next_time = compare_time + datetime.timedelta(days=1) if (now > next_time): print 'Doing a cleanup (' + str(datetime.datetime.now()) + ')' actions = Action.query.filter(Action.date <= past) action_count = helpers.get_query_count(actions) print str(action_count) + ' items to cleanup' if action_count > 0: logentry = Action( datetime.datetime.utcnow(), ConfigManager.NODE_NAME, 'Sync Master', '*****@*****.**', 'Cleanup ' + str(action_count) + ' logs older than ' + str(ConfigManager.CLEANUP_THRESHOLD) + ' days', 'Cleanup', 'L1', 0, 'Internal') db.session.add(logentry) actions.delete() db.session.commit() print 'Next cleanup @' + str(next_time) + ' (' + str( datetime.datetime.now()) + ')' self.lastCleanupTime = now
def add_action(self, action): from time import gmtime, strftime from models import Action import json timestamp = strftime("%Y-%m-%d %H:%M:%S", gmtime()) new_action = Action(action=json.dumps(action), timestamp=timestamp) self.session.add(new_action) self.session.commit()
def reset_action_live_votes(): reset_actions = Action.query(Action.used == False, Action.live_vote_value > 0).fetch() # Reset all actions that haven't been used, but have a live_vote_value, to zero for ra in reset_actions: # Set the actions live_vote_value to zero ra.live_vote_value = 0 ra.put()
def generate_actions(users, count): actions = list() user_count = users.__len__() - 1 for i in range(0, count): actions.append(Action(datetime.now(), users[random.randint(0, user_count)])) return actions
def label_is_for_load_action(self, project, labels): if not self.is_single_label(labels): return False label = self.get_label(labels) action = Action.query(ancestor=project.key).filter(Action.label == label).get() return action != None and action.type == "Load"
def testDeleteAction(self): TEST_USER_ID = 'testUserId' TEST_PHRASE = 'this is a test' TEST_LINK = 'https://www.google.com/shopping/express' accountKey = GetAccountKey(TEST_USER_ID) actionKey = InsertAction(TEST_USER_ID, TEST_PHRASE, TEST_LINK) DeleteAction(actionKey) self.assertEquals(0, len(Action.query(ancestor=accountKey).fetch(2)))
def label_is_for_load_action(self, project, labels): if not self.is_single_label(labels): return False label = self.get_label(labels) action = Action.query(ancestor=project.key).filter( Action.label == label).get() return (action != None and action.type == 'Load')
def get(self): actions = Action.query( Action.used == False).order(-Action.vote_value, Action.created).fetch() context = {'actions': actions, 'show': get_current_show(), 'session_id': str(self.session.get('id', '0')), 'item_count': len(actions)} self.response.out.write(template.render(self.path('add_actions.html'), self.add_context(context)))
def perform_action(actions, mention): if mention.message != '': primary_action = mention.message.split(' ')[0] if primary_action in actions: if len(mention.message.split(' ')) > 1: secondary_action = mention.message.split(' ')[1] if secondary_action in actions[primary_action]: #perform both actions action_data = "TEST DOUBLE ACTION" action = Action(mention.message, action_data, mention) return action #no secondary action specified return possible options usage = "usage: " + primary_action + " " + str( actions.get(primary_action)) action = Action(mention.message, usage, mention) return action else: action = Action(mention.message, None, mention) return action
def sync_user(current_user): if not current_user.is_authenticated: return error("User must be authenticated", 403) body = flask.request.get_json() if body is None: return error("Could not decode body as JSON", 400) last_updated_string = body.get("last_updated") if last_updated_string is None: return error("Last updated date and time is required", 400) # "Mon, 13 Apr 2020 22:46:09 GMT" server_sync_time_string = datetime.datetime.now( datetime.timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT") try: # "2020-04-06 18:07:22 -0000" last_updated = datetime.datetime.strptime(last_updated_string, "%Y-%m-%d %H:%M:%S %z") if last_updated.tzinfo is None: raise ValueError except ValueError: return error("Invalid last updated date and time", 400) # TODO: This is gross and I'm sure there's a better way to do this directly # in a database query initial_usergames = UserGame.select().where(UserGame.user == current_user) game_ids = [usergame.game_id for usergame in initial_usergames] games = Game.select().where( Game.id.in_(game_ids) & (Game.last_updated > last_updated)) usergames = UserGame.select().where(UserGame.game.in_(games)) actions = Action.select().where( Action.game.in_(games) & (Action.created > last_updated)) # TODO: This is gross and I'm sure there's a better way to do this directly # in a database query user_ids = [] for usergame in usergames: if (usergame.user_id not in user_ids): user_ids.append(usergame.user_id) # TODO: Hacky McHackface if current_user.id not in user_ids: user_ids.append(current_user.id) users = User.select().where( User.id.in_(user_ids) & (User.last_updated > last_updated)) return success(games=[game.to_json() for game in games], usergames=[usergame.to_json() for usergame in usergames], actions=[action.to_json() for action in actions], users=[user.to_json() for user in users], server_sync_time=server_sync_time_string)
def api_close_vote(): t_settings = TimeSettings.query.first() t_settings.status = 'closed' db.session.add(t_settings) current_user = Admin.query.filter_by(email=session['user']).first() action = Action(owner=current_user.id, type='closeelection', target_type='settings', text='Closed election', target_id=1) db.session.add(action) db.session.commit() return jsonify(status="OK")
def get(self, show_id): show = ndb.Key(Show, int(show_id)).get() available_actions = len(Action.query( Action.used == False).fetch()) context = {'show': show, 'now_tz': back_to_tz(get_mountain_time()), 'available_actions': available_actions, 'host_url': self.request.host_url, 'VOTE_AFTER_INTERVAL': VOTE_AFTER_INTERVAL} self.response.out.write(template.render(self.path('show.html'), self.add_context(context)))
def get_current_info(player, now=None): """ used in view f(Player) --> (PlayerState,Action) """ if not now: now = datetime.now() return { "reference_time": now, "player": player, "attribute_state": sorted(Thespian(player).snapshot(now).values(), key=lambda x: x["order"]), "last_action": Action.latest_action(player), }
def post(self): print 'Opening request received' checkAccessResult = security.checkUserAccessPrivleges(datetime.datetime.now(),g.user) print "Check user privileges for opening request: " + checkAccessResult if (checkAccessResult == "Access granted."): if datetime.datetime.now() > g.user.lastAccessDateTime + datetime.timedelta(minutes=config.NODE_LOG_MERGE): g.user.lastAccessDateTime = datetime.datetime.now() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Opening request ( ' + str(1) + ' attempts)', 'Opening request', 'L2', 0, 'Web based', Action.ACTION_OPENING_REQUEST, 1) print "Log-entry created" try: db.session.add(logentry) db.session.commit() except: db.session.rollback() return '', 401 else: lastlogEntry = Action.query.filter_by(logType='Opening request', userMail=g.user.email).order_by(Action.date.desc()).first() if lastlogEntry is not None: print str(lastlogEntry.synced) if lastlogEntry.synced is 0: print "is not None / False" lastlogEntry.date = datetime.datetime.utcnow() lastlogEntry.actionParameter += 1 lastlogEntry.logText = 'Opening request ( ' + str(lastlogEntry.actionParameter) + ' attempts)'; else: print "is not None / True" lastlogEntry.synced = 0 lastlogEntry.date = datetime.datetime.utcnow() lastlogEntry.actionParameter = 1 lastlogEntry.logText = 'Opening request ( ' + str(lastlogEntry.actionParameter) + ' attempts)'; print str(lastlogEntry.synced) else: print "is None" print "Log-entry is in merge-range ts = " + str(datetime.datetime.now()) + " last = " + str(g.user.lastAccessDateTime) + " merge = " + str(config.NODE_LOG_MERGE) + " minutes" try: db.session.commit() except: db.session.rollback() return '', 401 backgroundWorker.requestOpening = True return 'Access granted', 201 else: print "Check user privileges for opening request: " + checkAccessResult return checkAccessResult, 201 return '', 201
def change_money(people, money, action): for person in people: person.money += money person.save() assert action and action <> '' try: a = Action.objects.get(name=action) except: a = Action(name=action) a.save() if len(people) == 1: content = "{0}元".format(money) else: content = "每人{0:.3f}元".format(money) log = Log(action=a, content=content) log.save() for person in people: log.people.add(person) log.save()
def delete(self): if (g.user.syncMaster == 0): return make_response(jsonify({'error': 'Not authorized'}), 403) print 'action-log deletetion requested' Action.query.delete() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, '', 'Removed all actions after syncing', 'Remove actions after sync', 'L1', 0, 'Web based') db.session.add(logentry) db.session.commit() return '', 201
def add_action_to_game(current_user): if not current_user.is_authenticated: return error("User must be authenticated", 403) body = flask.request.get_json() if body is None: return error("Could not decode body as JSON", 400) game_id = body.get("game") if game_id is None: return error("Game required", 400) game = Game.get_or_none(Game.id == game_id) if game is None: return error("Unknown game", 400) if not game.have_all_players_accepted_invite: return error("Players have not all accepted invites yet", 400) action_json = body.get("action") if action_json is None: return error("Action required", 400) action = Action.create_without_saving(action_json, game) if not action.content_has_player: return error("Invalid action", 400) if not action.is_for_player(current_user.email): return error("Cannot play for another player", 400) try: game.load_initial_state() game.load_actions() except (engine.IllegalActionError, engine.IllegalSetupError) as e: return error("Error loading game: " + str(e), 400) try: game.apply_action(action) except (engine.IllegalActionError, engine.IllegalSetupError) as e: return error("Error applying new action: " + str(e), 400) action.save() game.update_current_user() game.last_updated = datetime.datetime.now(datetime.timezone.utc) game.save() for usergame in game.usergames: send_sync_notification(usergame.user_id) return success()
def api_update_note(): strings = Strings.query.first() text = request.args.get('text') strings.note = text app.config['NOTE'] = text db.session.commit() current_user = Admin.query.filter_by(email=session['user']).first() action = Action(owner=current_user.id, type='updatenote', target_type='settings', text='Updated admin note', target_id=1) # the settings objects only have 1 id - 1 db.session.add(action) db.session.commit() return jsonify(status="OK")
def delete(self, id): user = User.query.filter_by(id=id).first() if user != None: print 'delete user ' + user.firstName + ' ' + user.lastName + ' (' + user.email + ') from database' logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'User ' + user.firstName + ' on ' + user.lastName + ' removed', 'User removed', 'L2', 1, 'Web based') db.session.add(logentry) db.session.commit() User.query.filter(User.id == id).delete() db.session.commit() return '', 201
def post(self): form = DoorRegistrationForm() print 'Door registration request received' if not form.validate_on_submit(): return form.errors, 422 if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) print 'Request door info from ' + 'http://' + form.address.data + ':5000' + '/request/doorinfo' pwd = base64.b64decode(form.password.data) auth_token = 'Basic ' + base64.b64encode( "[email protected]:" + pwd) headers = {'Authorization': auth_token} try: response = requests.get('http://' + form.address.data + ':5000' + '/request/doorinfo', timeout=6, headers=headers) except: print "requested door unreachable" return 'requested door unreachable', 400 response_data = json.loads(response.content) newDoor = Door(name=response_data["name"], displayName=form.name.data, keyMask=response_data["keyMask"], address='http://' + form.address.data, local=0, password=pwd) logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Door ' + newDoor.name + ' on ' + newDoor.address + ' checked and registered', 'Door registered', 'L2', 1, 'Web based') try: db.session.add(logentry) db.session.commit() db.session.add(newDoor) db.session.commit() print "Added door to database" except IntegrityError: print "Problems to add door to database" return make_response( jsonify({'error': 'eMail already registered'}), 400) print "return new door data for request" return DoorSerializer().dump(newDoor).data
def post(self): print 'RFID assign request received' # check request paremeters (form) form = RFIDTagAssignForm() if not form.validate_on_submit(): return form.errors, 422 # check admin rights if g.user.role != 1: return make_response(jsonify({'error': 'Not authorized'}), 403) user = User.query.filter_by(email=form.email.data).first() if (user == None): return make_response(jsonify({'error': 'user not found'}), 400) if form.rfidTagId.data != None and form.rfidTagId.data != '': secretString = '' for i in range(0, 16): if i != 0: secretString = secretString + '-' num = random.randrange(0, 256) secretString = secretString + format(num, '02X') user.cardID = form.rfidTagId.data user.cardSecret = secretString user.cardAuthBlock = 1 user.cardAuthSector = 4 user.cardAuthKeyA = config.RFID_GLOBAL_PASSWORD user.cardAuthKeyB = "FF-FF-FF-FF-FF-FF" print "User-secret: >" + str(user.cardSecret) + "<" print "User-keyA: >" + str(user.cardAuthKeyA) + "<" print "User-keyB: >" + str(user.cardAuthKeyB) + "<" if (backgroundWorker.assignRFIDTag(user) == False): print 'Error while assigning cardID ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName db.session.rollback() return make_response(jsonify({'error': 'user not found'}), 400) else: logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, g.user.firstName + ' ' + g.user.lastName, g.user.email, 'Assign RFID-tag ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName, 'Card administration', 'L2', 0, 'Card based') db.session.add(logentry) db.session.commit() print 'Assigned cardID ' + form.rfidTagId.data + ' to ' + user.firstName + ' ' + user.lastName return '', 201
def pull(): current_time = time.time() rjson = data.getdata('sound,temperature', current_time, DEAMON_TIME_INTERVAL, 10) averageSound = calcAver(rjson['data']['datastreams'][0]['datapoints']) averageTem = calcAver(rjson['data']['datastreams'][1]['datapoints']) if averageSound < CRY_SOUND_THRESHOD and averageTem > INBED_TEMPERATURE_THRESHOD: action = Action(action_type='sleep') elif averageSound > CRY_SOUND_THRESHOD and averageTem > INBED_TEMPERATURE_THRESHOD: action = Action(action_type='cry') else: action = Action(action_type='missing') action.save()
def submit_action(): if g.user is None or g.user.is_banned: abort(404) activity_id = int(request.args.get("activity_id", "-1")) link = request.args.get("link", None) if activity_id <= 0 or link is None: return jsonify(**{"status": False, "msg": gettext("Wrong params")}) last = Action.last_by_user(g.user.id) if last is not None and (datetime.datetime.now() - last.creation_date ).total_seconds() < ACTION_TIMEOUT: return jsonify( **{ "status": False, "msg": gettext("To many actions. Take a break, please.") }) adder = DBModelAdder() adder.start() if Action.is_exist(adder, activity_id, link): return jsonify(**{ "status": False, "msg": gettext("This link has been already added.") }) action = Action(g.user.id, activity_id, None, link) adder.add(action) adder.done() return jsonify( **{ "status": True, "msg": gettext("Action was added. It will be reviewed soon. Thank you!") })
def api_unlock_user(): id = request.args.get('id') user = User.query.filter_by(id=id).first() user.in_timeout = False current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='lockuser', target_type='user', text='Unlocked user ({0})'.format( user.email), target_id=user.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
def load_actions(): """Records of actions been applied to place results by users""" action_code_list = ['sav','hbh'] for i in range(250): #generating an arbitrary number of actions (250 at most) user_id = randint(1, 1000) #load_users() will generate 1000 registered users place_id = randint(1, 3030) #load_places() will generate 3030 searchable places action_code = choice(action_code_list) #checking if action has already been added to actions table action_in_db = db.session.query(Action).filter(Action.user_id==user_id, Action.place_id==place_id, Action.action_code==action_code).first() if not action_in_db: action = Action(user_id=user_id, place_id=place_id, action_code=action_code) db.session.add(action) db.session.commit()
def get_action_from_label(self, label, create_action_if_needed, project): action = Action.query(ancestor=project.key).filter( Action.label == label).get() if (action == None and create_action_if_needed): # Create a temp store of actions created just for this run. if label not in self.__temp_actions: action = Action(parent=project.key, name=label, type='Response', label=label, x_axis=0, y_axis=0, y_axis_max='duration') action.put() self.__temp_actions[label] = action else: action = self.__temp_actions[label] return action
def timer_cycle(self): self.requestTimer += 1 if self.requestTimer >= 4: self.requestTimer = 0 try: self.checkRFIDTag() except Exception, e: import traceback print traceback.format_exc() logentry = Action(datetime.datetime.utcnow(), config.NODE_NAME, 'Background Worker', '*****@*****.**', 'Error: ' + str(traceback.format_exc()), 'Error occured', 'L1', 0, 'Internal') db.session.add(logentry) db.session.commit()
def api_unlock_option(): id = request.args.get('id') option = Option.query.filter_by(id=id).first() option.live = True current_user = Admin.query.filter_by(email=session['user']).first() action = Action( owner=current_user.id, type='unlockoption', target_type='option', text='unlocked option ({0})'.format( option.name), target_id=option.id) db.session.add(action) db.session.commit() return jsonify(status="OK")
class TestAction(TestCase): """Tests related to the action""" def setUp(self): self.bandit = Bandit() self.action = Action(self.bandit) def test_action_value_is_gaussian(self): """ Verify that our action will get a correct value from N(mu, sigma) - mu: the mean, here 0 - sigma: the variance, here 1 """ results = [Action(self.bandit).value for x in range(5000)] law_1 = get_percent([x for x in results if x > 0], results) self.assertAlmostEqual(law_1, 50, delta=2, msg="%s%% of results are " "above mu instead of around 51%%" % law_1) law_2 = get_percent([x for x in results if x > -1 and x < 1], results) self.assertAlmostEqual(law_2, 68, delta=2, msg="%s%% of results are " "above mu instead of around 68%%" % law_2) def test_gauss_with_numpy(self): """We use numpy, let's add some verifications""" mu, sigma = 0, 1 value = np.random.normal(mu, sigma, 1000) diff_mean = abs(mu - np.mean(value)) self.assertLess(diff_mean, 0.12, "diff mean = %s > 0.1" % diff_mean) diff_vari = abs(sigma - np.std(value, ddof=1)) self.assertLess(diff_vari, 0.12, "diff vari = %s > 0.1" % diff_vari) def test_action_can_play(self): """Let's play and check that action got a reward""" action = self.action # shortcut [action.play() for x in range(1000)] lim = [action.mu - 3 * action.sigma, action.mu + 3 * action.sigma] rewards_in_range = [r for r in action.rewards if lim[0] <= r <= lim[1]] percent = get_percent(rewards_in_range, action.rewards) self.assertAlmostEqual(percent, 85.0, delta=15, msg="%s%% instead of " "99,7%% for a Normal Distribution" % percent) # TODO verify why it comes to 86% sometimes ! def test_action_mean_reward(self): """Test that an action keep an history of rewards and that mean_reward become closer to value after multiples plays""" [self.action.play() for i in range(1, 1000)] vari = abs(self.action.sigma - np.std(self.action.rewards, ddof=1)) self.assertLess(vari, 0.12, "diff variance = %s > 0.1" % vari)
def get_single_load_action_from_project (self, project): # Check all Actions. actions = Action.query(ancestor=project.key) load_action = None for action in actions: if action.type == 'Load': # If we've just hit the first Load Action, set it, otherwise # unset it and break out of the loop. if load_action == None: load_action = action else: load_action = None break # Return either None or the only load action return load_action
def make_quarterback_action(qb_data, collaboration, i): quarterback_name_number = qb_data['QB'][i] if quarterback_name_number == None or quarterback_name_number.strip() == '': return athlete = find_athlete(quarterback_name_number) action, created_ = Action.get_or_create( collaboration = collaboration, athlete = athlete, action_type = 'QB' ) for key in qb_data.keys(): if key != 'QB': value = qb_data[key][i] if value not in [None, '']: print(qb_data[key][i]) Observation.get_or_create( action = action, name = key, value = qb_data[key][i] )
def get_action_shared_site(user): if Action.get_action_count_for_user(user, Action.SHARE_SITE_FACEBOOK) > 0 or Action.get_action_count_for_user(user, Action.SHARE_SITE_TWITTER) > 0: return True else: return False
def testInsertEntity(self): act = Action() act.phrase = 'test phrase' act.put() self.assertEquals(1, len(Action.query().fetch(2)))
def post(self, show_id): show = ndb.Key(Show, int(show_id)).get() # Admin is starting the show if self.request.get('interval_vote') and self.context.get('is_admin', False): # Get the next interval next_interval = show.get_next_interval(show.current_interval) # If there is a next interval if next_interval != None: # Set the current interval to the next interval show.current_interval = next_interval # Set the start time of this interval vote show.interval_vote_init = get_mountain_time() show.put() # Reset all actions that haven't been used, but have a live_vote_value, to zero reset_action_live_votes() # Admin is starting item vote elif self.request.get('test_vote') and self.context.get('is_admin', False): show.test = None # Delete all live voting test votes for lvt in LiveVotingTest.query().fetch(): lvt.key.delete() # Delete all voting test objects for vt in VotingTest.query().fetch(): vt.key.delete() # Create a set of five test votes VotingTest(name="I'M JAZZED! START THE SHOW ALREADY!").put() VotingTest(name="I'm VERY interested in... whatever this is...").put() VotingTest(name="Present").put() VotingTest(name="Meh").put() VotingTest(name="If you notice me sleeping in the audience, try and keep it down. Thanks.").put() show.test_vote_init = get_mountain_time() show.put() # Admin is starting hero vote elif self.request.get('hero_vote') and self.context.get('is_admin', False): show.hero_vote_init = get_mountain_time() show.put() # Admin is starting villain vote elif self.request.get('villain_vote') and self.context.get('is_admin', False): show.villain_vote_init = get_mountain_time() show.put() # Admin is starting incident vote elif self.request.get('incident_vote') and self.context.get('is_admin', False): # Set all actions that haven't been used, but have a live_vote_value, to zero reset_action_live_votes() show.incident_vote_init = get_mountain_time() show.put() # Admin is starting the shapeshifter vote elif self.request.get('shapeshifter_vote') and self.context.get('is_admin', False): show.shapeshifter_vote_init = get_mountain_time() show.put() # Admin is starting the lover vote elif self.request.get('lover_vote') and self.context.get('is_admin', False): show.lover_vote_init = get_mountain_time() show.put() # Admin is starting a recap elif self.request.get('recap') and self.context.get('is_admin', False): show.recap_init = get_mountain_time() show.recap_type = self.request.get('recap') show.put() # Admin is locking/unlocking the voting elif self.request.get('lock_vote') and self.context.get('is_admin', False): # Toggle the lock/unlock show.locked = not show.locked show.put() available_actions = len(Action.query( Action.used == False).fetch()) context = {'show': show, 'now_tz': back_to_tz(get_mountain_time()), 'available_actions': available_actions, 'host_url': self.request.host_url, 'VOTE_AFTER_INTERVAL': VOTE_AFTER_INTERVAL} self.response.out.write(template.render(self.path('show.html'), self.add_context(context)))
def post(self): deleted = None unused_deleted = False show_list = self.request.get_all('show_list') action_list = self.request.get_all('action_list') item_list = self.request.get_all('item_list') character_list = self.request.get_all('character_list') theme_list = self.request.get_all('theme_list') delete_unused = self.request.get_all('delete_unused') # If action(s) were deleted if action_list: for action in action_list: action_entity = ndb.Key(Action, int(action)).get() # Get all the related action votes and delete them action_votes = ActionVote.query(ActionVote.action == action_entity.key).fetch() for av in action_votes: av.key.delete() action_entity.key.delete() deleted = 'Action(s)' # If theme(s) were deleted if theme_list: for theme in theme_list: theme_entity = ndb.Key(Theme, int(theme)).get() # Get all the related theme votes and delete them theme_votes = ThemeVote.query(ThemeVote.theme == theme_entity.key).fetch() for tv in theme_votes: tv.key.delete() theme_entity.key.delete() deleted = 'Theme(s)' # If show(s) were deleted if show_list: for show in show_list: show_entity = ndb.Key(Show, int(show)).get() show_actions = ShowAction.query(ShowAction.show == show_entity.key).fetch() # Delete the actions that occurred within the show for show_action in show_actions: action = show_action.player_action.get().action if action: action.delete() show_action.player_action.delete() show_action.key.delete() # Delete player associations to the show show_players = ShowPlayer.query(ShowPlayer.show == show_entity.key).fetch() for show_player in show_players: show_player.key.delete() # Delete all Role votes role_votes = RoleVote.query(RoleVote.show == show_entity.key).fetch() for role_vote in role_votes: role_vote.key.delete() # Delete the theme used in the show, if it existed if show_entity.theme: show_entity.theme.delete() show_entity.key.delete() deleted = 'Show(s)' # Delete ALL un-used things if delete_unused: # Delete Un-used Actions unused_actions = Action.query(Action.used == False).fetch() for unused_action in unused_actions: # Get all the related action votes and delete them action_votes = ActionVote.query(ActionVote.action == unused_action.key).fetch() for av in action_votes: av.key.delete() # Delete the un-used actions unused_action.key.delete() deleted = 'All Un-used Actions' context = {'deleted': deleted, 'unused_deleted': unused_deleted, 'shows': Show.query().fetch(), 'actions': Action.query(Action.used == False).fetch(), 'themes': Theme.query(Theme.used == False).fetch()} self.response.out.write(template.render(self.path('delete_tools.html'), self.add_context(context)))
def get(self): context = {'shows': Show.query().fetch(), 'actions': Action.query(Action.used == False).fetch(), 'themes': Theme.query(Theme.used == False).fetch()} self.response.out.write(template.render(self.path('delete_tools.html'), self.add_context(context)))
def InsertAction(userId, phrase, link): act = Action(parent=GetAccountKey(userId)) act.keywords = SplitPhrase(phrase) act.redirect_link = link return act.put()
def sync_cycle(self): now = datetime.datetime.now() lasttime = self.lastSyncTime if config.NODE_SYNC_CYCLIC == True: compare_time = lasttime + datetime.timedelta(minutes=config.NODE_SYNC_CYCLE) if now > compare_time: self.lastSyncTime = now print "Next sync @" + str( self.lastSyncTime + datetime.timedelta(minutes=config.NODE_SYNC_CYCLE) ) + " (" + str(datetime.datetime.now()) + ")" else: if self.forceSync == True: self.forceSync = False else: return else: compare_time = lasttime.replace(hour=4, minute=15, second=0, microsecond=0) if compare_time > lasttime: next_time = compare_time else: next_time = compare_time + datetime.timedelta(days=1) if now > next_time: self.lastSyncTime = now print "Next sync @" + str(next_time) + " (" + str(datetime.datetime.now()) + ")" else: if self.forceSync == True: self.forceSync = False else: return if config.NODE_MASTER == False: return print "Doing a sync cycle" doorList = Door.query.all() for doorSync in doorList: if doorSync.local == 1: print "Sync actions of " + doorSync.name + " (local)" else: print "Sync actions of " + doorSync.name self.sync_door_log(doorSync) print "Update actions" self.update_users_and_actions() logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, "Sync Master", "*****@*****.**", "Update & synchronized actions and users", "Update & Sync.", "L1", 0, "Internal", ) logentry.synced = 1 db.session.add(logentry) db.session.commit() # sync user of all doors for doorSync in doorList: if doorSync.local == 1: print "Sync user of " + doorSync.name + " (local)" else: print "Sync user of " + doorSync.name self.sync_door_user(doorSync) if doorSync.local == 0: logentry = Action( datetime.datetime.utcnow(), config.NODE_NAME, "Sync Master", "*****@*****.**", "Synchronized " + doorSync.displayName + " (" + doorSync.name + ")", "Synchronization", "L1", 0, "Internal", ) logentry.synced = 1 db.session.add(logentry) db.session.commit()
def setUp(self): self.bandit = Bandit() self.action = Action(self.bandit)