def performTest(dataService, k): dataService.fetchData() v = Validation(dataService, k) errorID3 = [] errorC45 = [] time = datetime.datetime.now().time() for i in range(k): print(f'Iteration: {i}, error rate:') train, test = v.split_to_train_test(i) id3_algorithm = ID3(train, dataService.attrValues, dataService.classes) tree = id3_algorithm.generateTree() errorID3.append(id3_algorithm.evaluate(test)) c45_algorithm = C45(train, dataService.attrValues, dataService.classes) c45_algorithm.adjustWithC45(tree) errorC45.append(c45_algorithm.evaluateC45Tree(test)) Test.save_to_file(k, time, errorID3[i], errorC45[i]) MeanErrorID3 = round(100 * sum(errorID3) / k, 2) MeanErrorC45 = round(100 * sum(errorC45) / k, 2) Test.save_to_file(k, time, MeanErrorID3, MeanErrorC45) Test.save_to_file(k, time, len(train), (len(train) / len(v.data)) * 100) print(f'ID3 mean error: {MeanErrorID3}%') print(f'C45 mean error: {MeanErrorC45}%')
def new_from_input(dictionary): """ desc: creates a new Child object from user input input param: the dictionary where the object will be put returns: none, adds child to dictionary and prints confirmation """ #user input - validates using methods at top of script first_name = Validation.validate_alpha( "Enter the child's first name: ").title() last_name = Validation.validate_alpha( "Enter the child's last name: ").title() age = Validation.validate_age("Enter the child's age: ") guardian_first_name = Validation.validate_alpha( "Enter the guardian's first name: ").title() SMS_contact = Validation.validate_phone( "Enter the SMS phone number of the guardian: ") #creates new child instance and puts in dictionary with key #that follows established convention new_child = first_name.title() + last_name[0].upper() dictionary.update({ new_child: Child(first_name, last_name, age, guardian_first_name, SMS_contact) }) #prints confirmation to user print("New Child Created.") print(dictionary[new_child])
def patch(id): try: v.validateID(id) product = Product.query.filter( Product.userID == current_user.id).filter( Product.iD == id).first() v.validateNotNoneProduct(product) field = None attr = None for attr in Product.attributes(): try: field = request.json[attr] break except KeyError: pass getattr(product, 'set' + attr[0].upper() + attr[1:])(field) result = productSchema.dump(product) db.session.commit() return jsonify({'status': 'success'}, {'patched product': result}), 204 except Exception as e: return jsonify({'status': 'fail'}, {'message': str(e)}), 404
def get(self, email): # Get values server = request.headers.get('server') # Validate required fields validation = Validation() validation.add_required_field('email', email) validation.add_required_field('server', server) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) success, code, message = user_service.send_email_confirm( user.id, server) db.session.commit() if success: logging.info('LocalUser-controller: RequestConfirm: success: %s', user.id) return {'success': True} else: if code == 10: return Failures.rate_exceeded() return {'success': False, 'message': message, 'code': 520}
def __init__(self, name, salary, firstday, lastday): for i in range(len(turtle)): setattr(self, turtle[i], None) self.__name = v.validName(name) self.__salary = v.validFloat(salary) self.__firstday = v.validDate(firstday) self.__lastday = v.validDate(lastday)
def write_in_json_file(self, file_name): Validation.validateFileName(file_name, "json") with open(file_name, 'w', encoding='utf-8') as outfile: json.dump([ob.__dict__ for ob in self.lst], outfile, ensure_ascii=False) outfile.close()
def post(self): # Get values server = request.headers.get('server') email = request.form.get('email') password = request.form.get('password') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('password', password) if not validation.is_valid(): return validation.get_validation_response() # Validate user exists, is validated and is not blocked user = user_services.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if not user.confirmed: return Failures.email_not_confirmed(email) if user.blocked: return Failures.user_blocked(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) if not rate_limiting_services.has_sufficient_tokens(user.id, 'failed-password', 1): return Failures.rate_exceeded() # The password might not be encoded correctly when submitted. This # could cause the check_password method to fault. We trap that # possibility and address it here. try: if not user_services.check_password(user.id, password): rate_limiting_services.consume_tokens(user.id, 'failed-password', 1) return Failures.wrong_password(email) except TypeError: return Failures.password_unknown_format("Unicode-objects must be encoded before hashing") db.session.commit() logging.info('Authenticate-controller: Authenticate: success: %s', email) return { 'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name, 'authentication-source': user.auth_source, 'bdmonth': user.birth_month, 'bdyear': user.birth_year, 'parent-email': user.parent_email, 'parent-email-source': user.parent_email_source }}
def join_spree_get_amount(update, context): global current_spree_id text = update.message.text validation = Validation(None) validation_result = validation.isValidAmount(text) if validation_result == "": buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]] keyboard = InlineKeyboardMarkup(buttons) update.message.reply_text(text='Successfully joined Spree! ✅', reply_markup=keyboard) amt = "%.2f" % (float(text)) user_name = update.effective_user['username'] spree_ref = db.collection(u'Sprees').document(current_spree_id) spree_obj = spree_ref.get().to_dict() total_people = spree_obj.get('total_people') total_people.append(user_name) people_num = spree_obj.get('people_num') + 1 curr_amt = float(spree_obj.get('current_amount')) + float(amt) remaining_amt = float(spree_obj.get('remaining_amount')) - float(amt) spree_ref.set( { u'total_people': total_people, u'people_num': people_num, u'current_amount': curr_amt, u'remaining_amount': remaining_amt }, merge=True) if remaining_amt <= 0.0: #send shit here send_text = 'Your spree ' + spree_obj.get( 'Spree_name' ) + ', is complete! 🎉\nThe minimum spending of $' + str( spree_obj.get('min_amount') ) + ' has been met. \n\nHere are your fellow Spreenters: ' for list_username in total_people: send_text += '\n @' + list_username print(send_text) user_db = db.collection(u'Users') for list_username in total_people: temp_user = user_db.where(u'Username', u'==', list_username).limit(1).stream() for temp_o in temp_user: lol = temp_o.to_dict() list_userid = lol['User_id'] bot.sendMessage(chat_id=list_userid, text=send_text) spree_ref.delete() current_spree_id = None return SHOWING else: bot.sendMessage(chat_id=update.effective_user['id'], text=validation_result)
def generateBoard(self, filled): i = 0 while i < filled: number = random.randrange(1, 10) x = random.randrange(0, 9) y = random.randrange(0, 9) valid = Validation(self.board) if valid.valid(number, x, y): self.board[x][y] = number i += 1
def get(id): try: v.validateID(id) product = Product.query.filter(Product.iD == id).first() v.validateNotNoneProduct(product) result = productSchema.dump(product) return jsonify({'status': 'success'}, {'product': result}), 200 except Exception as e: return jsonify({'status': 'fail'}, {'message': str(e)}), 404
def train(self): # Define vars for training self.defineVars() print("Training variables:") print(len(self.config["trainVars"]), self.config["trainVars"]) # Get stuff from input ROOT files self.importData() self.config["nBkgTrainEvents"] = self.loader.getNumBkgEvents() self.config["nSigTrainEvents"] = self.loader.getNumSigEvents() scales = self.loader.getDataScales() means = self.loader.getDataMeans() regShape, domainShape, discoShape, inputShape = self.loader.getShapes() # Make model print("\n----------------Preparing training model------------------") # Kelvin says no self.gpu_allow_mem_grow() model = self.make_model(scales, means, regShape, discoShape, inputShape) callbacks = self.get_callbacks() # Training model print("\n----------------Training model------------------") result_log = model.fit(self.loader, epochs=self.config["epochs"], callbacks=callbacks, validation_data=self.testLoader) if self.saveAndPrint: # Model Visualization print("\n----------------Printed model layout------------------") self.plot_model(model) # Save trainig model as a protocol buffers file print("\n----------------Saving model------------------") self.save_model_pb(model) #Plot results print("\n----------------Validation of training------------------") val = Validation(model, self.config, self.loader, self.valLoader, self.evalLoader, self.testLoader, result_log) metric = val.makePlots(self.doQuickVal, self.config["evalMass"], self.config["evalModel"]) del val #Clean up training del model return metric
def post(self): # Get values server = request.headers.get('server') email = request.form.get('email') password = request.form.get('password') #browser = request.form.get('browser') #ip_address = request.form.get('ipAddress') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('password', password) #validation.add_required_field('browser', browser) #validation.add_required_field('ipAddress', ip_address) if not validation.is_valid(): return validation.get_validation_response() # Validate user exists, is validated and is not blocked user = user_services.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if not user.confirmed: return Failures.email_not_confirmed() if user.blocked: return Failures.user_blocked() if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) if not rate_limiting_services.has_sufficient_tokens( user.id, 'failed-password', 1): return Failures.rate_exceeded() if not user_services.check_password(user.id, password): rate_limiting_services.consume_tokens(user.id, 'failed-password', 1) db.session.commit() return Failures.wrong_password() db.session.commit() logging.info('Authenticate-controller: Authenticate: success: %s', user.id) return { 'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name, 'authentication-source': user.auth_source } }
def generate_list(l, context): """ The function that generates list according to context type. """ context = Validation.validateListGeneration(context) if isinstance(context.strategy, FirstStrategy): par = Validation.validateInt(input("Enter amount of elements: ")) else: par = Validation.validateFileName(input("Enter file name: ")) pos = Validation.validateInt(input("Enter position: ")) context.generate_list(l, pos, par)
def save_spree(update, context): global current_field global current_spree global bot #retrieve saved fields and save it into database validation = Validation(current_spree) validation_result = validation.validation_check() # validation fail if validation_result != '': errortext = 'Oops! Seems like something went wrong:' buttons = [[ InlineKeyboardButton(text='Back', callback_data=str(CREATE_SPREE_MENU)) ]] keyboard = InlineKeyboardMarkup(buttons) update.callback_query.edit_message_text(text=errortext + "\n" + validation_result, reply_markup=keyboard) return CREATING_SPREE name = current_spree.spree_name min = current_spree.min_amount curr = current_spree.current_amount user_name = update.effective_user['username'] current_spree.total_people.append(user_name) #else sucess #reset global vars text = 'Spree name: ' + name + '\nMinimum Spending Amount: $' + ( "%.2f" % (float(min))) + '\nCurrent Amount: $' + ("%.2f" % (float(curr)) + '\n\nSpree saved!✅') buttons = [[InlineKeyboardButton(text='Okay', callback_data=str(END))]] # save current_spree to db user_name = update.effective_user['username'] keyboard = InlineKeyboardMarkup(buttons) update.callback_query.edit_message_text(text=text, reply_markup=keyboard) sprees_db = db.collection(u'Sprees') sprees_db.add(current_spree.to_dict()) current_spree.reset_values() current_field = None context.user_data[START_OVER] = True return SHOWING
def read_json_file(self, file_name): Validation.validateFileName(file_name, "json") f = open(file_name, encoding='utf-8') file = json.load(f) for i, product in enumerate(file): try: product["u_id"] = str(uuid.uuid4()) self.lst.append(Product(**product)) except ValueError as e: print("Line" + str(i * (len(product) + 1) + 3) + ": " + str(e)) continue f.close()
def post(self): username = str(self.request.get("username")) password = str(self.request.get("password")) check = Validation() key = check.encrypt(username, password) if check.validate(username, password): self.response.headers.add_header('Set-Cookie', 'key=%s ; Path=/' % key) self.redirect('/notes') else: self.redirect('/login')
def delete(id): try: v.validateID(id) product = Product.query.filter(Product.iD == id).first() v.validateNotNoneProduct(product) db.session.delete(product) db.session.commit() result = productSchema.dump(product) return jsonify({'status': 'success'}, {'deleted product': result}), 204 except Exception as e: return jsonify({'status': 'fail'}, {'message': str(e)}), 404
def get(self, bucket_type, id_user, count): # Validate required fields validation = Validation() validation.add_required_field('bucket_type', bucket_type) validation.add_required_field('id_user', id_user) validation.add_required_field('count', count) if not validation.is_valid(): return validation.get_validation_response() # Parse numbers try: id_user = int(id_user) except ValueError: return Failures.not_a_number('idUser', id_user) try: count = int(count) except ValueError: return Failures.not_a_number('count', count) # Validate user exists, is validated and is not blocked user = user_services.get_user(id_user) if user is None: return Failures.unknown_user_id(id_user) if user.blocked: return Failures.user_blocked() if not user.confirmed: return Failures.email_not_confirmed() bucket_types = app.config['CLOUD_SESSION_PROPERTIES'][ 'bucket.types'].split(',') if bucket_type not in bucket_types: return Failures.unknown_bucket_type(bucket_type) result, next_time = rate_limiting_services.consume_tokens( user.id, bucket_type, 1) if not result: db.session.commit() return Failures.rate_exceeded( next_time.strftime("%Y-%m-%d %H:%M:%S")) db.session.commit() logging.info( 'RateLimiting-controller: ConsumeMultiple: success: %s (%s - %s)', id_user, bucket_type, count) return {'success': True}
def run_validation(self): while True: try: validation = Validation( validation_addr=self.__va_addr, host=self.__va_host, batch_size=100, db_host=self.__host, port=self.__port, key=self.__key) validation.run() except Exception: pass sleep(self.__va_time)
def post(self): # Get values server = request.headers.get('server') email = request.form.get('email') password = request.form.get('password') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('password', password) if not validation.is_valid(): return validation.get_validation_response() # Validate user exists, is validated and is not blocked user = user_services.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if not user.confirmed: return Failures.email_not_confirmed(email) if user.blocked: return Failures.user_blocked(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) if not rate_limiting_services.has_sufficient_tokens(user.id, 'failed-password', 1): return Failures.rate_exceeded() if not user_services.check_password(user.id, password): rate_limiting_services.consume_tokens(user.id, 'failed-password', 1) db.session.commit() return Failures.wrong_password(email) db.session.commit() logging.info('Authenticate-controller: Authenticate: success: %s', email) return {'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name, 'authentication-source': user.auth_source, 'bdmonth': user.birth_month, 'bdyear': user.birth_year, 'parent-email': user.parent_email, 'parent-email-source': user.parent_email_source }}
def LDA_results(self, sample): num, statement = self.Check_format(sample) if num == 0: sample_lower = sample.lower() sample_list = sample_lower.split(',') test = {} test['Map'] = 'UNK' test['Name'] = 'UNK pathway' test['EC'] = [sample_list] df_validate = pd.DataFrame(test) df_result = Validation().compare_test_train_docs( df_validate, self.data_dataframe, self.MODEL, self.dictionary) df_sorted = df_result.sort_values(by=['Similarity']) return df_sorted else: return "None"
class OpenProjectInfo(QtGui.QWidget): """ Class ProjectInfo accept model information from user """ def __init__(self): super(OpenProjectInfo, self).__init__() self.obj_validation = Validation() def body(self): self.projDir = QtGui.QFileDialog.getExistingDirectory() if self.obj_validation.validateOpenproj(self.projDir) == True: print "Pass open project test" self.obj_Appconfig = Appconfig() self.obj_Appconfig.current_project['ProjectName'] = str( self.projDir) else: print "Failed open project test" reply = QtGui.QMessageBox.critical( None, "Error Message", '''<b> Error: The project doesn't contain .proj file.</b><br/> <b>Please select the proper project directory else you won't be able to perform any operation</b>''', QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Ok: self.body() elif reply == QtGui.QMessageBox.Cancel: pass else: pass
def main(config, args): config["result_dir"] = args.path print(config["result_dir"]) torch.manual_seed(config["seed"]) random.seed(config["seed"]) np.random.seed(config["seed"]) path_data = config['path'] + "/safe_set_data.pth" if config['load_data']: data_loader = torch.load(path_data) data_loader.setBatchSize(config['n_batch'], config['train_val_ratio']) else: data_loader = DataLoader.DataLoader(config) torch.save(data_loader, path_data) print(data_loader.n_all_batches) model = SafeSet.SafeSet(config) path_model = config['path'] + "/safe_set_model.pth" path_model_results = config["result_dir"] + "/safe_set_model.pth" if not config['load_model']: trainer = Trainer.Trainer(config) trainer.train(model, data_loader) torch.save(model, path_model) torch.save(model, path_model_results) else: model = torch.load(path_model) validation = Validation.Validation(config) validation.validate(model, data_loader) validation.validateTest(model, data_loader) validation.validateTestUnseen(model, data_loader) validation.save_val() validation.save_model(model)
def testing(): train_X_POS,train_X_CO,train_Y,test_X_POS,test_X_CO,test_Y = train_test_split() super_model = SuperModel() super_model.fit_co(train_X_CO, train_Y) super_model.fit_pos(train_X_POS, train_Y) predicted_Ys = {} for ex_id in test_Y.keys(): predicted_Ys[ex_id] = super_model.predict(test_X_CO[ex_id],test_X_POS[ex_id]) print "predicted:",predicted_Ys[ex_id],"true:",test_Y[ex_id] V = Validation(test_Y,predicted_Ys) print V.MSE() print V.worst_ten()
def runValidation(): validation = Validation() data = validation.run() #prepare data arr = np.array(data) m = np.mean(arr, axis=0) std = np.std(arr, axis=0) means = [] stddev = [] for i in range(30): means.append(m) stddev.append(std) plt.plot(data, 'r-') plt.plot(range(30), means, 'b:') plt.plot(range(30), stddev, 'g--') #green dashed line plt.show()
def run(self, message): try: validation = Validation() broadcast = validation.decode(self.address, self.netmask)['broadcast'] # se o endereço for de broadcast da rede então a mensagem é disparada para todos if message.destino.address == broadcast: self.flooding(message) else: self.filtering(message) # pergunto se já conheço except: self.flooding(message) finally: # switch aprende as portas self.learning(message.origin) self.learning(message.destino)
def print_res(func): try: n = Validation.validateInt(input("Enter n (amount of pairs): ")) l = func(n) print("Sequence of %d coprime pairs is: %s." % (n, l)) except ValueError as e: print(e)
def addNumber(self, number, x, y): valid = Validation(self.board) if not valid.isZero(x, y): print('- - - - - - - - - - - - - ') print('- CANNOT MODIFY THIS FIELD - ') print('- - - - - - - - - - - - - ') return self.printBoard() elif not valid.validRow(number, x): print('- - - - - - - - - - - - - ') print('- NUMBER EXIST IN ROW ' + str(x) + ' - ') print('- - - - - - - - - - - - - ') return self.printBoard() elif not valid.validColumn(number, y): print('- - - - - - - - - - - - - ') print('- NUMBER EXIST IN COLUMN ' + str(y) + ' - ') print('- - - - - - - - - - - - - ') return self.printBoard() elif not valid.validBox(number, x, y): boxName = BoxName() print('- - - - - - - - - - - - - ') print('- NUMBER EXIST IN ' + boxName.show(x // 3, y // 3) + ' - ') print('- - - - - - - - - - - - - ') return self.printBoard() elif not valid.valid(number, x, y): self.board[x][y] = number print('- - - - - - - - - - - - - ') print('- - - - - NEW - - - - - ') print('- - - - - - - - - - - - - ') return self.printBoard()
def patchSingle(self, id): unit = self.model.query.filter(self.model.id == id).first() v.validateNotNoneObject(unit) field = None attr = None for attr in self.model.attributes(): try: field = request.json[attr] break except KeyError: pass getattr(unit, 'set' + attr[0].upper() + attr[1:])(field) result = self.schema.dump(unit) return result
def del_between_indexes(l): """ The function deletes elements between two indexes. """ index1, index2 = Validation.validateLowHeight( tuple( map(Validation.validateInt, input("Enter index1 and index2: ").split()))) l.delete_between_pos(index1, index2)
def register(): try: data = [] args = ['first_name', 'last_name', 'email', 'password'] args_validate = [ Validation.name_validator, Validation.name_validator, Validation.email_validator, Validation.pass_validator ] errors = {} Validation.name_validator(request.args['first_name']) for x in range(0, len(args)): if args[x] in request.args: result = args_validate[x](request.args[args[x]]) if result is True: if x == 3: key = hashlib.pbkdf2_hmac( 'sha256', str(request.args[args[x]]).encode('utf-8'), salt, 100000) storage = salt + key data.append(storage) else: data.append(request.args[args[x]]) else: errors[args[x]] = result else: errors[args[x]] = 'Missing' if not errors: columns = '(' + ', '.join(args) + ')' data = tuple(data) to_do = 'INSERT INTO users' + columns + ' VALUES (%s, %s, %s, %s)' cursor.execute(to_do, data) db.commit() return jsonify({ 'status': '200', 'message': 'Successful registration' }) else: return jsonify({'status': '400', 'errors': errors}) except MySQLdb.IntegrityError: return jsonify({ 'status': '400', 'message': 'Such email already registered' })
def get(self, bucket_type, id_user, count): # Validate required fields validation = Validation() validation.add_required_field('bucket_type', bucket_type) validation.add_required_field('id_user', id_user) validation.add_required_field('count', count) if not validation.is_valid(): return validation.get_validation_response() # Parse numbers try: id_user = int(id_user) except ValueError: return Failures.not_a_number('idUser', id_user) try: count = int(count) except ValueError: return Failures.not_a_number('count', count) # Validate user exists, is validated and is not blocked user = user_services.get_user(id_user) if user is None: return Failures.unknown_user_id(id_user) if user.blocked: return Failures.user_blocked() if not user.confirmed: return Failures.email_not_confirmed() bucket_types = app.config['CLOUD_SESSION_PROPERTIES']['bucket.types'].split(',') if bucket_type not in bucket_types: return Failures.unknown_bucket_type(bucket_type) result, next_time = rate_limiting_services.consume_tokens(user.id, bucket_type, 1) if not result: db.session.commit() return Failures.rate_exceeded(next_time.strftime("%Y-%m-%d %H:%M:%S")) db.session.commit() logging.info('RateLimiting-controller: ConsumeMultiple: success: %s (%s - %s)', id_user, bucket_type, count) return {'success': True}
def join_spree_get_amount(update, context): global current_spree_id text = update.message.text validation = Validation(None) validation_result = validation.isValidAmount(text) if validation_result == "": buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]] keyboard = InlineKeyboardMarkup(buttons) update.message.reply_text(text='Successfully joined Spree!', reply_markup=keyboard) amt = "%.2f" % (float(text)) user_name = update.effective_user['username'] spree_ref = db.collection(u'Sprees').document(current_spree_id) spree_obj = spree_ref.get().to_dict() total_people = spree_obj.get('total_people') total_people.append(user_name) people_num = spree_obj.get('people_num') + 1 curr_amt = spree_obj.get('current_amount') + float(amt) remaining_amt = spree_obj.get('remaining_amount') - float(amt) spree_ref.set( { u'total_people': total_people, u'people_num': people_num, u'current_amount': curr_amt, u'remaining_amount': remaining_amt }, merge=True) if remaining_amt <= 0: #send shit here spree_ref.delete() current_spree_id = None return SHOWING else: bot.sendMessage(chat_id=update.effective_user['id'], text=validation_result)
def get(self, email): # Get server URL server = request.headers.get('server') logging.info("Requesting email confirmation for %s from server %s", email, server) # Validate required fields validation = Validation() validation.add_required_field('email', email) validation.add_required_field('server', server) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) success, code, message = user_service.send_email_confirm(user.id, server) db.session.commit() if success: logging.info('LocalUser-controller: RequestConfirm: success: %s', user.id) return {'success': True} else: if code == 10: return Failures.rate_exceeded() elif code == 99: return { 'success': False, 'message': message, 'code': 540 } else: return { 'success': False, 'message': message, 'code': 520 }
def get(self, email): # Get values server = request.headers.get('server') # Validate required fields validation = Validation() validation.add_required_field('email', email) validation.add_required_field('server', server) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) if not user.confirmed: return Failures.email_not_confirmed(user.email) success, code, message = user_service.send_password_reset(user.id, server) db.session.commit() if success: logging.info('LocalUser-controller: RequestPasswordReset: success: %s', user.id) return {'success': True} else: if code == 10: return Failures.rate_exceeded() return { 'success': False, 'message': message, 'code': 520 }
def post(id_user): screen_name = request.form.get('screenname') # Validate required fields validation = Validation() validation.add_required_field('id-user', id_user) validation.add_required_field('screenname', screen_name) if not validation.is_valid(): return validation.get_validation_response() # Validate the id parameter as an integer try: id_user = int(id_user) except ValueError: return Failures.not_a_number('idUser', id_user) # Validate user exists, is validated and is not blocked user = user_service.get_user(id_user) if user is None: return Failures.unknown_user_id(id_user) # Attempt to retrieve the proposed screen name to ensure that it is available user_by_email = user_service.get_user_by_screen_name(screen_name) if user_by_email is not None: if user.id != user_by_email.id: return Failures.screen_name_already_in_use(screen_name) # The screen name is available, Assign it to the user profile user.screen_name = screen_name db.session.commit() logging.info('User-controller: doInfoChange: success: %s (%s)', id_user, user.screen_name) return {'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name, 'authentication-source': user.auth_source, 'bdmonth': user.birth_month, 'bdyear': user.birth_year, 'parent-email': user.parent_email, 'parent-email-source': user.parent_email_source }}
def post(self): # Get values email = request.form.get('email') # User account email address token = request.form.get('token') # Token assigned to account during account registration # Validate required fields validation = Validation() validation.add_required_field('email', email) validation.add_required_field('token', token) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) # Delete expired tokens ConfirmToken.query.filter(ConfirmToken.validity < datetime.datetime.now()).delete() db.session.flush() confirm_token = ConfirmToken.query.filter_by(token=token).first() if confirm_token is None: # Unknown token return {'success': False, 'code': 510} if confirm_token.id_user != user.id: # Token is not for this user return {'success': False, 'code': 510} # Set user account status to 'Confirmed' user.confirmed = True # Delete the account confirmation token; it is no longer required db.session.delete(confirm_token) # Commit the user account changes db.session.commit() logging.info('LocalUser-controller: DoConfirm: success: %s', user.id) return {'success': True}
class OpenProjectInfo(QtGui.QWidget): """ This class is called when User click on Open Project Button """ def __init__(self): super(OpenProjectInfo, self).__init__() self.obj_validation = Validation() def body(self): self.obj_Appconfig = Appconfig() self.openDir = self.obj_Appconfig.default_workspace["workspace"] #print "default workspace is now 1", self.openDir self.projDir=QtGui.QFileDialog.getExistingDirectory(self,"open",self.openDir) if self.obj_validation.validateOpenproj(self.projDir) == True: #print "Pass open project test" #self.obj_Appconfig = Appconfig() self.obj_Appconfig.current_project['ProjectName'] = str(self.projDir) if os.path.isdir(self.projDir): print "true" for dirs, subdirs, filelist in os.walk(self.obj_Appconfig.current_project["ProjectName"]): directory = dirs files = filelist self.obj_Appconfig.project_explorer[dirs] = filelist json.dump(self.obj_Appconfig.project_explorer, open(self.obj_Appconfig.dictPath,'w')) self.obj_Appconfig.print_info('Open Project called') self.obj_Appconfig.print_info('Current Project is ' + self.projDir) return dirs, filelist else: #print "Failed open project test" self.obj_Appconfig.print_error("The project doesn't contain .proj file. Please select the proper directory else you won't be able to perform any operation") reply = QtGui.QMessageBox.critical(None, "Error Message",'''<b> Error: The project doesn't contain .proj file.</b><br/> <b>Please select the proper project directory else you won't be able to perform any operation</b>''',QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Ok: self.body() self.obj_Appconfig.print_info('Open Project called') self.obj_Appconfig.print_info('Current Project is ' + self.projDir) elif reply == QtGui.QMessageBox.Cancel: self.obj_Appconfig.print_info('No Project opened') else: pass
def post(id_user): locale = request.form.get('locale') # Validate required fields validation = Validation() validation.add_required_field('id-user', id_user) validation.add_required_field('locale', locale) if not validation.is_valid(): return validation.get_validation_response() # Parse numbers try: id_user = int(id_user) except ValueError: return Failures.not_a_number('idUser', id_user) # Validate user exists, is validated and is not blocked user = user_service.get_user(id_user) if user is None: return Failures.unknown_user_id(id_user) user.locale = locale db.session.commit() logging.info('User-controller: doLocaleChange: success: %s (%s)', id_user, user.screen_name) return {'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name, 'authentication-source': user.auth_source, 'bdmonth': user.birth_month, 'bdyear': user.birth_year, 'parent-email': user.parent_email, 'parent-email-source': user.parent_email_source }}
def post(): # Get values server = request.headers.get('server') email = request.form.get('email') password = request.form.get('password') password_confirm = request.form.get('password-confirm') locale = request.form.get('locale') screen_name = request.form.get('screenname') # COPPA support birth_month = request.form.get('bdmonth') birth_year = request.form.get('bdyear') parent_email = request.form.get('parent-email') parent_email_source = request.form.get('parent-email-source') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('password', password) validation.add_required_field('password-confirm', password_confirm) validation.add_required_field('locale', locale) validation.add_required_field('screenname', screen_name) # COPPA support validation.add_required_field('bdmonth', birth_month) validation.add_required_field('bdyear', birth_year) if parent_email: validation.check_email('parent-email', parent_email) if not validation.is_valid(): return validation.get_validation_response() # Verify user email address validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate email is not yet used existing_user = user_service.get_user_by_email(email) if existing_user is not None: return Failures.email_already_in_use(email) # Validate screen name is not yet used existing_user = user_service.get_user_by_screen_name(screen_name) if existing_user is not None: return Failures.screen_name_already_in_use(screen_name) # Validate password strength and confirm if password != password_confirm: return Failures.passwords_do_not_match() if not user_service.check_password_complexity(password): return Failures.password_complexity() # Write user details to the database id_user = user_service.create_local_user( server, email, password, locale, screen_name, birth_month, birth_year, parent_email, parent_email_source) # Send a confirmation request email to user or parent (result, errno, mesg) = user_service.send_email_confirm(id_user, server) if result: # Commit the database record db.session.commit() logging.info('User-controller: register success: %s', id_user) # Create user return {'success': True, 'user': id_user} else: logging.error("Unable to register user. Error %s: %s", errno, mesg) return {'success': False, 'user': 0}
def post(self, id_user): # Get values old_password = request.form.get('old-password') password = request.form.get('password') password_confirm = request.form.get('password-confirm') # Validate required fields validation = Validation() validation.add_required_field('id_user', id_user) validation.add_required_field('old-password', old_password) validation.add_required_field('password', password) validation.add_required_field('password_confirm', password_confirm) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user(id_user) if user is None: return Failures.unknown_user_id(id_user) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) # Validate password strength and confirm if password != password_confirm: return Failures.passwords_do_not_match() if not user_service.check_password_complexity(password): return Failures.password_complexity() if not user_service.check_password(id_user, old_password): # Token is not for this user return {'success': False, 'code': 530} salt, password_hash = user_service.get_password_hash(password) user.password = password_hash user.salt = salt db.session.commit() logging.info('LocalUser-controller: PasswordChange: success: %s', user.id) return {'success': True}
def post(self, email): # Get values token = request.form.get('token') password = request.form.get('password') password_confirm = request.form.get('password-confirm') # Validate required fields validation = Validation() validation.add_required_field('email', email) validation.add_required_field('token', token) validation.add_required_field('password', password) validation.add_required_field('password-confirm', password_confirm) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) if user.auth_source != 'local': return Failures.wrong_auth_source(user.auth_source) # Validate password strength and confirm if password != password_confirm: return Failures.passwords_do_not_match() if not user_service.check_password_complexity(password): return Failures.password_complexity() # Delete expired tokens ResetToken.query.filter(ResetToken.validity < datetime.datetime.now()).delete() db.session.flush() reset_token = ResetToken.query.filter_by(token=token).first() if reset_token is None: # Unkown token return {'success': False, 'code': 510} if reset_token.id_user != user.id: # Token is not for this user return {'success': False, 'code': 510} salt, password_hash = user_service.get_password_hash(password) user.password = password_hash user.salt = salt db.session.delete(reset_token) db.session.commit() logging.info('LocalUser-controller: DoPasswordReset: success: %s', user.id) return {'success': True}
def post(self): # Get values server = request.headers.get('server') email = request.form.get('email') source = request.form.get('source') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('source', source) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate user exits user = user_service.get_user_by_email(email) if user is None: return Failures.unknown_user_email(email) # Validate auth source if user.auth_source != source: return Failures.wrong_auth_source(user.auth_source) logging.info('OAuth-controller: Validate: success: %s', user.id) return {'success': True, 'user': { 'id': user.id, 'email': user.email, 'locale': user.locale, 'screenname': user.screen_name }}
from Validation import Validation validation = Validation() validation.start()
def __init__(self): super(NewProjectInfo, self).__init__() self.obj_validation = Validation() self.obj_appconfig = Appconfig()
def __init__(self): super(OpenProjectInfo, self).__init__() self.obj_validation = Validation()
class NewProjectInfo(QtGui.QWidget): """ This class is called when User create new Project. """ def __init__(self): super(NewProjectInfo, self).__init__() self.obj_validation = Validation() self.obj_appconfig = Appconfig() def createProject(self,projName): """ This function create Project related directories and files """ #print "Create Project Called" self.projName= projName self.workspace = self.obj_appconfig.default_workspace['workspace'] #self.projName = self.projEdit.text() self.projName = str(self.projName).rstrip().lstrip() #Remove leading and trailing space self.projDir = os.path.join(self.workspace,str(self.projName)) #Validation for newProject if self.projName == "": self.reply = "NONE" else: self.reply = self.obj_validation.validateNewproj(str(self.projDir)) #Checking Validations Response if self.reply == "VALID": print "Validated : Creating project directory" #create project directory try: os.mkdir(self.projDir) self.close() self.projFile = os.path.join(self.projDir,self.projName+".proj") f = open(self.projFile,"w") except: #print "Some Thing Went Wrong" self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('Unable to create project. Please make sure you have write permission on '+self.workspace) self.msg.setWindowTitle("Error Message") f.write("schematicFile " + self.projName+".sch\n") f.close() #Now Change the current working project newprojlist = [] #self.obj_appconfig = Appconfig() self.obj_appconfig.current_project['ProjectName'] = self.projDir newprojlist.append(self.projName+'.proj') self.obj_appconfig.project_explorer[self.projDir] = newprojlist self.obj_appconfig.print_info('New project created : ' + self.projName) self.obj_appconfig.print_info('Current project is : ' + self.projDir) json.dump(self.obj_appconfig.project_explorer, open(self.obj_appconfig.dictPath,'w')) return self.projDir, newprojlist elif self.reply == "CHECKEXIST": #print "Project already exist" self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('The project "'+self.projName+'" already exist.Please select the different name or delete existing project') self.msg.setWindowTitle("Error Message") elif self.reply == "CHECKNAME": #print "Name is not proper" self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('The project name should not contain space between them') self.msg.setWindowTitle("Error Message") elif self.reply == "NONE": #print "Empty Project Name" self.msg = QtGui.QErrorMessage(self) self.msg.showMessage('The project name cannot be empty') self.msg.setWindowTitle("Error Message") def cancelProject(self): self.close()
def post(self): # Get values server = request.headers.get('server') email = request.form.get('email') locale = request.form.get('locale') screen_name = request.form.get('screenname') source = request.form.get('source') # Validate required fields validation = Validation() validation.add_required_field('server', server) validation.add_required_field('email', email) validation.add_required_field('locale', locale) validation.add_required_field('screenname', screen_name) validation.add_required_field('source', source) validation.check_email('email', email) if not validation.is_valid(): return validation.get_validation_response() # Validate email is not yet used existing_user = user_service.get_user_by_email(email) if existing_user is not None: return Failures.email_already_in_use(email) # Validate screen name is not yet used existing_user = user_service.get_user_by_screen_name(screen_name) if existing_user is not None: return Failures.screen_name_already_in_use(screen_name) id_user = user_service.create_oauth_user(server, email, source, locale, screen_name) db.session.commit() logging.info('OAuth-controller: create success: %s', id_user) # Create user return {'success': True, 'user': id_user}