def __init__(self, username, password, debug_mode=False): self.username = username self.password = password self.device_id = utils.generate_device_id(utils.md5_sum(username + password)) self.uuid = utils.generate_uuid(True) self.s = requests.Session() self.token = "" self.rank_token = "" self.username_id = "" self.phone_id = utils.generate_uuid(True) self.csrf_token = "" self.debug_mode = debug_mode
def create_secure_user(session: Session, first_name: str, last_name: str, email: str, password: str) -> User: password_salt = utils.generate_uuid() password_hashed = utils.hash_password(password_raw=password, salt=password_salt) auth_token = utils.generate_uuid() result = crud_user.create_user(session, first_name, last_name, email, password_hashed, password_salt, auth_token) return result
def post(self): request_data = sign_up_for_class_data() class_id = request_data['class_id'] class_data_model = ClassDataModel.find_by_class_id(class_id) if class_data_model is None: return {'error': True, 'message': 'Resource not found'} sign_up_model = SignUpForClassModel() now = datetime.datetime.now() sign_up_model.created_on = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second) sign_up_model.student_id = request_data['userid'] sign_up_model.class_uuid = request_data['class_id'] sign_up_model.item_uuid = generate_uuid() class_sign_up_data_model = ClassSignupDataModel() class_sign_up_data_model.set_data_fields(sign_up_model) check_classes = class_sign_up_data_model.find_all_by_student_id( request_data['userid']) if check_classes is not None: for item in check_classes: if item.class_uuid == sign_up_model.class_uuid: return { 'error': True, 'message': 'You have already signed up for this class' } class_sign_up_data_model.save_to_db() return {'error': False, 'message': 'Successfully signed up for class'}
def login(self): resp = self.send_request( 'si/fetch_headers/?challenge_type=signup&guid=' + utils.generate_uuid(), None) if resp.status_code != 200: return False data = { 'phone_id': self.phone_id, '_csrftoken': resp.cookies['csrftoken'], 'username': self.username, 'guid': self.uuid, 'device_id': self.device_id, 'password': self.password, 'login_attempt_count': '0' } resp = self.send_request('accounts/login/', self.generate_signature(json.dumps(data))) if resp.status_code != 200: return False resp_json = utils.resp_to_json(resp) self.logged_in_user = resp_json["logged_in_user"] self.username_id = self.logged_in_user["pk"] self.rank_token = "%s_%s" % (self.username_id, self.uuid) self.token = resp.cookies["csrftoken"] return True
async def left_right_predict(self, sid, args): """ Endpoint for making predictions with trained p300 classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to make prediction on } :returns: prediction results in the format { 'uuid': client UUID 'left': True or False result of model prediction } """ # initialize service if it does not exist already if self.services.get('left_right') is None: self.services['left_right'] = LeftRightService() # load arguments, generate UUID if none is provided uuid = args['uuid'] if args['uuid'] != 'None' else generate_uuid() data = args['data'] results = self.services['left_right'].predict(uuid=uuid, data=data) return results
def post(self): data = get_registration_info() is_user_valid, error_message = validate_register_user(data) if not is_user_valid: return error_message user = UserFactory.factory(data['usertype']) user.username = data['username'] user.password = generate_hash(data['password']) user.uuid = generate_uuid() if UserDataModelFactory.factory(user.usertype).find_by_username( user.username): return { 'error': True, 'message': 'User {} already exists'.format(user.username) } new_user = UserDataModelFactory.factory(user.usertype) new_user.set_data_fields(user) try: new_user.save_to_db() access_token = create_access_token(identity=user.username) refresh_token = create_refresh_token(identity=user.username) return { 'error': False, 'message': 'User {} was created'.format(user.username), 'access_token': access_token, 'refresh_token': refresh_token, 'user_id': user.uuid } except: return {'error': True, 'message': 'Something went wrong'}, 500
async def p300_train(self, sid, args): """ Endpoint for training p300--given enough data, will train classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to use for training 'p300': True or False } :returns: None if there is not enough data for training, or the current model accuracy in the format { 'uuid': client UUID 'acc': current training accuracy } """ # initialize service if it does not exist already if self.services.get('p300') is None: self.services['p300'] = P300Service() # load arguments, generate UUID if none is provided uuid = args['uuid'] if args['uuid'] != 'None' else generate_uuid() data = args['data'] p300 = args['label'] results = self.services['p300'].train(uuid=uuid, data=data, p300=p300) return results
def create_song(user): form = request.form song_file = request.files['file'] import os filename, file_extension = os.path.splitext(song_file.filename) if file_extension != ".wav" and file_extension != ".mp3": abort(400) song_new_filename = utils.generate_uuid() song_url = aws.upload_song(song_new_filename, file_extension, song_file) session = Session() crud_song.create_song(session, user_id=user.id, song_title=form['title'], song_artist=form['artist'], song_album=form['album'], song_release_year=int(form['releaseYear']), song_url=song_url) session.close() return Response(status=200)
async def on_message(message): if message.author == client.user: return user_id = message.author content = message.content response = EventHandler.execute(content, user_id, generate_uuid()) if response: await message.channel.send(response)
async def train_classifier(self, sid, args): """ Endpoint for training classifier--given enough data, will train classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to use for training 'p300': True or False } :returns: None if there is not enough data for training, or the current model accuracy in the format { 'uuid': client UUID 'acc': current training accuracy } """ # load arguments, generate UUID if none is provided uuid = args['uuid'] if args['uuid'] != 'None' else generate_uuid() data = args['data'] p300 = args['p300'] # initialize if empty self.inputs[uuid] = self.inputs.get(uuid, []) self.targets[uuid] = self.targets.get(uuid, []) self.inputs[uuid].append(np.array(data)) self.targets[uuid].append(np.array(p300)) results = {'uuid': uuid, 'acc': None} if len(self.targets[uuid]) % 10 == 0 and len(self.targets[uuid]) >= 10: X = np.array(self.inputs[uuid]) y = np.array(self.targets[uuid]) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # Note in Barachant's ipynb, 'erpcov_mdm' performed best. 'vect_lr' is the # universal one for EEG data. # train self.clf[uuid] = ml.ml_classifier(X_train, y_train, classifier=None, pipeline='vect_lr') acc = self.clf[uuid].score(X_test, y_test) self.save_classifier(uuid) results['acc'] = acc return results
def signup(self, teacher): user = user_register.user password = user_register.password user.sender = generate_uuid() user.created_at = timestamp() try: use_repo = UserRepo() if use_repo.save(user, password_hash(password)): return user except Exception: traceback.print_exc() return None
def add_college(self, fields: dict): ref_id = generate_uuid() college = College(ref_id=ref_id, **fields, created_at=get_current_time(), updated_at=get_current_time()) db.session.add(college) try: db.session.commit() except Exception as e: error_orig = str(e.orig).replace("(", "").replace(")", "").split(",")[1].strip().replace("'", "").replace('"', '') raise IntegrityError(message=error_orig) return college
def main(): mkdir_if_not_exists(IMAGE_DIR) empty_dir(IMAGE_DIR) grab_area = read_grab_area() crop_areas = find_crop_areas() for _ in tqdm(range(2 ** 11)): ss = grab_screen(grab_area) draw_crop_areas(ss, crop_areas) for img in crop_images(ss, crop_areas): save_path = os.path.join(IMAGE_DIR, generate_uuid() + '.png') cv2.imwrite(save_path, img) refresh(grab_area) time.sleep(1)
def add_department(self, fields: str): ref_id = generate_uuid() department = Department(ref_id=ref_id, **fields, created_at=get_current_time(), updated_at=get_current_time()) db.session.add(department) try: db.session.commit() except Exception as e: print(str(e.orig)) error_orig = str(e.orig).replace("(", "").replace(")", "").split(",")[1].strip().replace("'", "").replace('"', '').split(":")[0] raise IntegrityError(message=error_orig) return department
def process_video(video_path: str): vid = cv2.VideoCapture(video_path) success, image = vid.read() count = 0 vid_uid = generate_uuid() os.makedirs(f"static/images/videoprocessing/{vid_uid}") while success and count <= VIDEO_FRAME_LIMIT: filename = f"static/images/videoprocessing/{vid_uid}/{count}.jpg" cv2.imwrite(filename, image) success, image = vid.read() count += 1 save_image_db(f"{filename}") if vid.isOpened(): vid.release() shutil.rmtree(f"static/images/videoprocessing/{vid_uid}") os.remove(video_path)
async def train_classifier_test(self, sid, args): """ Tests endpoint for training classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to use for training 'p300': True or False } :returns: dummy results of training """ args = json.loads(args) uuid = args.get('uuid', generate_uuid()) results = {'uuid': uuid, 'acc': random.random()} return results
def update_user(user, user_id): data = request.get_json() session = Session() user.first_name = data[ 'firstName'] if data['firstName'] != "" else user.first_name user.last_name = data[ 'lastName'] if data['lastName'] != "" else user.last_name user.password_hashed = data[ 'password'] if data['password'] != "" else user.password_hashed password_salt = utils.generate_uuid( ) if data['password'] != "" else user.password_salt user.password_hashed = utils.hash_password( password_raw=user.password_hashed, salt=password_salt) if data['password'] != "" else user.password_hashed crud_user.update_user(session, user.id, user.first_name, user.last_name, None, user.password_hashed, password_salt) session.close() return Response(status=200)
def post(self): class_data = get_create_class_request_data() is_valid, payload = validate_create_class(class_data) if not is_valid: return payload usertype = class_data['usertype'] teacher_id = class_data['userid'] class_name = class_data['class_name'] end_day = class_data['end_day'] end_month = class_data['end_month'] end_year = class_data['end_year'] class_description = class_data['class_description'] class_uuid = generate_uuid() created_on = datetime.datetime.utcnow username = get_jwt_identity() if not UserDataModelFactory.factory(usertype).find_by_username( username): return { 'error': True, 'message': 'Not valid user {}'.format(username) } new_class = ClassModel() new_class.initiate_resource(teacher_id, username, created_on, class_name) now = datetime.datetime.now() new_class.created_on = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second) new_class.class_end_date = datetime.datetime(int(end_year), int(end_month), int(end_day), 0, 0, 0) new_class.class_uuid = class_uuid new_class.class_description = class_description class_data_model = ClassDataModel() class_data_model.set_data_fields(new_class) current_class_name = class_data_model.find_by_class_name(class_name) is_already_entity_name = class_data_model.save_to_db() if current_class_name: return {'error': True, 'message': 'Class name must be unique'} if is_already_entity_name: return {'error': False, 'message': 'successfully added class'} return {'error': True, 'message': 'Something went wrong'}
def save(self): """ Save method is triggered with save button on GUI. All the parameters are passed to a db methods whose task is to save them in db. If the save operation is successful then you'll get True as output and a dialog message will be displayed other False will be returned and you'll get appropriate message. """ entries = self.get_entries() if entries: entries['face_encoding'] = self.key_points entries['submitted_by'] = self.user entries['case_id'] = generate_uuid() self.save_to_db(entries) else: QMessageBox.about(self, "Error", "Please fill all entries")
async def test_predict(self, sid, args): """ Tests endpoint for making predictions with trained classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to make prediction on } :returns: dummy prediction results, including a True or False for P300 and a confidence score """ args = json.loads(args) uuid = args.get('uuid', generate_uuid()) results = { 'uuid': uuid, 'p300': random.choice([True, False]), 'score': random.random() } return results
def authenticate(self, username, password): """ Authenticates the user and upon successful authentication creates a new session and returns the session token. Authentication is done by verifying the password with it's hash. """ # Authenticate user = self.backend.get_user(username) if not user: raise errors.Unauthorized() is_success = sha256_crypt.verify(password, user.hashed_password) session_token = utils.generate_uuid() if is_success else None # Record the login attempt self.backend.insert_login_attempt(username, session_token) if not is_success: raise errors.InvalidLogin() # Create the session on successful login self.backend.create_session(session_token, username) return session_token
def adminAddSubmit(request): if "login_user" not in request.session: return redirect("/") adminAddView = loader.get_template('../UI/AddViewer.html') context = {} if request.method == 'POST': fname = request.POST["txtName"] fullname = fname.split(" ") if len(fullname)!=2: context["error_msg"] = "Full Name Required" return HttpResponse(adminAddView.render(context, request)) email = request.POST["txtEmail"] user = Teacher() user.first_name = fullname[0] user.last_name = fullname[1] user.email = email confirmation = generate_uuid() time = timestamp() context["user"] = user if not fname: context["error_msg"] = "Name field required" elif not email: context["error_msg"] = "Email field required" else: try: use_repo = UserRepo() subject = "Your account has been added" message = "Enter this confirmation code to register "+confirmation from_email = settings.EMAIL_HOST_USER to_list = [email] send_mail(subject, message, from_email, to_list, fail_silently=False) if use_repo.save(user, confirmation, time): context["success_msg"] = "Teacher Added, Confirmation Code is "+confirmation except Exception: traceback.print_exc() context["error_msg"] = "Something went wrong" return HttpResponse(adminAddView.render(context, request))
def update_song(user, song_id): form = request.form session = Session() song = crud_song.get_song(session, song_id=song_id) if not song: session.close() abort(404) if song.user_id != user.id: session.close() abort(403) song.title = form['title'] if 'title' in form else song.title song.artist = form['artist'] if 'artist' in form else song.artist song.album = form['album'] if 'album' in form else song.album song.release_year = form[ 'releaseYear'] if 'releaseYear' in form else song.release_year if 'file' in request.files: song_file = request.files['file'] import os filename, file_extension = os.path.splitext(song_file.filename) if file_extension != ".wav" and file_extension != ".mp3": session.close() abort(400) song_new_filename = utils.generate_uuid() song.url = aws.upload_song(song_new_filename, file_extension, song_file) crud_song.update_song(session, song) session.close() return Response(status=200)
def post(self): request_data = get_add_assignment_data() is_request_valid, payload = validate_add_assignment(request_data) if not is_request_valid: return payload class_ = ClassDataModel.find_by_class_id(request_data['class_id']) class_name = class_.class_name class_id = request_data['class_id'] assignment_title = request_data['assignment_title'] assignment_content = request_data['assignment_content'] end_day = request_data['end_day'] end_month = request_data['end_month'] end_year = request_data['end_year'] teacher_id = request_data['userid'] teacher_name = request_data['username'] now = datetime.datetime.now() created_on = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second) assignment_model = AssignmentModel() assignment_model.initiate_resource(teacher_id, teacher_name, created_on, class_name) assignment_model.assignment_id = generate_uuid() assignment_model.class_id = class_id assignment_model.teacher_id = teacher_id assignment_model.assignment_title = assignment_title assignment_model.assignment_content = assignment_content assignment_model.deadline = datetime.datetime(int(end_year), int(end_month), int(end_day), 0, 0, 0) assignment_data_model = AssignmentDataModel() assignment_data_model.set_data_fields(assignment_model) saved = assignment_data_model.save_to_db() if saved: return {'error': False, 'message': 'Successfully added'} else: return {'error': True, 'message': 'Error saving to db'}
async def retrieve_prediction_results(self, sid, args): """ Endpoint for making predictions with trained classifier :param sid: Socket IO session ID, automatically given by connection :param args: arguments from client. This should be in the format { 'uuid': client UUID 'data': EEG data to make prediction on } :returns: prediction results in the format { 'uuid': client UUID 'p300': True or False result of model P300 prediction 'score': confidence value of prediction between 0 and 1 } """ # load arguments, generate UUID if none is provided uuid = args['uuid'] if args['uuid'] != 'None' else generate_uuid() data = args['data'] # prepare data for prediction data = np.array(data) data = np.expand_dims(data, axis=0) # load classifier if not already loaded if self.load_classifier(uuid): p300 = self.clf[uuid].predict(data)[0] else: return 'Cannot load classifier and make prediction' # currently we do not have a confidence method score = 1 results = {'uuid': uuid, 'p300': p300, 'score': random.random()} return results
def post(self): request_data = submit_assignment_data() signed_up_student = ClassSignupDataModel.find_by_class_id_and_student_id( request_data['class_id'], request_data['userid']) existing_submission = SubmissionDataModel.find_by_student_id_and_assignment_id( request_data['userid'], request_data['assignment_id']) is_valid, payload = validate_new_submission(request_data, signed_up_student, existing_submission) if not is_valid: return payload submission_model = SubmissionModel() submission_model.submission_id = generate_uuid() submission_model.assignment_id = request_data['assignment_id'] submission_model.class_id = request_data['class_id'] submission_model.class_name = request_data['class_name'] submission_model.student_id = request_data['userid'] submission_model.student_name = request_data['username'] submission_model.teacher_id = request_data['teacher_id'] submission_model.teacher_name = request_data['teacher_name'] submission_model.content = request_data['assignment_content'] now = datetime.datetime.now() submission_model.created_on = datetime.datetime( now.year, now.month, now.day, now.hour, now.minute, now.second) submission_data_model = SubmissionDataModel() submission_data_model.set_data_fields(submission_model) successful_submission = submission_data_model.save_to_db() if successful_submission: return { 'error': False, 'message': 'Assignment submitted successfully' } return { 'error': True, 'message': 'A problem occurred while saving to database' }
def __init__(self, ip=C.LOCALHOST): self.ip = ip self.uuid = F.generate_uuid() self.server = None
"""Encloses the string with quotes if needed. It does not escape characters.""" if SAFE_CHARS.match(x): return x else: return '"%s"' % x if __name__ == '__main__': metrics = None try: conf = MetricsConfig() conf.__dict__[VCPU] = 'core' conf.__dict__[NET] = 'sum all' conf.__dict__[DISK] = 'sum all' if has_uuid_module: uuid_text = uuid.uuid4() else: uuid_text = generate_uuid() conf.__dict__[TOKEN] = uuid_text metrics = Metrics(conf, None, formatters.FormatSyslog('', 'le', ''), True) metrics.start() time.sleep(600) # Is there a better way? except KeyboardInterrupt: print >>sys.stderr, "\nTerminated" if metrics: metrics.cancel()
characters.""" if SAFE_CHARS.match(x): return x else: return '"%s"' % x if __name__ == '__main__': metrics = None try: conf = MetricsConfig() conf.__dict__[VCPU] = 'core' conf.__dict__[NET] = 'sum all' conf.__dict__[DISK] = 'sum all' if has_uuid_module: uuid_text = uuid.uuid4() else: uuid_text = generate_uuid() conf.__dict__[TOKEN] = uuid_text metrics = Metrics(conf, None, formatters.FormatSyslog('', 'le', ''), True) metrics.start() time.sleep(600) # Is there a better way? except KeyboardInterrupt: print >> sys.stderr, "\nTerminated" if metrics: metrics.cancel()
async def generate_uuid_handler(self, sid, args): """Handler for sending a request to the server to generate a UUID""" return generate_uuid()
async def generate_uuid_handler(self, sid, args): """Handler for sending a request to the server to generate a UUID""" uuid = generate_uuid() await self.sio_app.emit('generate_uuid', uuid)