def login(username, passw, format, apikey): """\b ------------------------------------------- User log in command. ------------------------------------------- User authorization level: None REST API call: /login \b ------------------------------------------- NOTE: If you are logged in with another user account, you have to logout before you can log in again. ------------------------------------------- """ validation.valid(apikey) validation.usercheck(username) validation.passwcheck(passw) if (os.path.isfile(paths.token_path)): click.echo('A user is already logged in!') else: p = {'username': username , 'password': passw, 'format': format, 'apikey': apikey} service = 'login' click.echo() click.echo(click.style('Logging in...', fg='cyan')) click.echo() response = requests.post(url=f'{paths.baseURL}/{service}/', params=p) if response.status_code == 200: if format == 'json': res = json.loads(response.text) f = open(paths.token_path, "w") f.write(res['token']) click.echo(click.style('Login successful!', fg='green')) f.close() else: #f is a temporary f = open(paths.temporary_path, 'w') f.write(response.text) f.close() #now f is the token file f = open(paths.token_path, "w") with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: f.write(str(rows['token'])) click.echo(click.style('Login successful!', fg='green')) f.close() else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2])
def logout(format, apikey): """\b ------------------------------------------- User log out command. ------------------------------------------- User authorization level: Connected user REST API call: /logout \b ------------------------------------------- NOTE: If you are not logged in, you cannot logout (OBVIOUSLY!). Don't try to trick us! ------------------------------------------- """ validation.valid(apikey) validation.user() click.echo('You are about to log out.') click.echo('Continue? '+click.style('[y/n]',fg='cyan'), nl=False) c = click.getchar() click.echo() if c=='y': f = open(paths.token_path, "r") token = f.readline() f.close() p = {'format': format, 'apikey': apikey} h = {'Authorization':'Token '+token} service = 'logout' click.echo() click.echo(click.style('Logging out...', fg='cyan')) click.echo() response = requests.post(url=f'{paths.baseURL}/{service}/', headers=h, params=p) if response.status_code == 200: os.remove(paths.token_path) click.echo(click.style('Logout complete!', fg='green')) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2]) elif c=='n': click.echo() click.echo(click.style('Abort...', fg='cyan')) click.echo() time.sleep(1) click.echo('You are still logged in.') else: click.echo() click.echo('Error: Invalid input.')
def post(self): username, password = self.request.get("username"), self.request.get("password") verify, email = self.request.get("verify"), self.request.get("email") errors = validation.valid(username, password, verify, email) error_user, error_password, error_verify, error_email = "", "", "", "" #check if username already exists in googgledb b=db.GqlQuery("Select * from Users where username=:1", username) user = b.get() if user: error_user="******" username = "" self.write_form(username=username, error_user=error_user, email=email) else: if sum(errors)==0: #if there are no errors, redirect to success page global username #put username in cookie self.response.headers.add_header("set-cookie", "username=%s" %str(username)) #store user info in database a = Users(username=username, password=password, email=email) a.put() self.response.headers.add_header("set-cookie", "username=%s" %str(username)) self.redirect("/packinglist/generator") else: error_user, error_password, error_verify, error_email = "", "", "", "" if errors[0]==1: error_user="******" if errors[1]==1: error_password="******" if errors[2]==1: error_verify="Password Mismatch" if errors[3]==1: error_email="Invalid Email" self.write_form(username, error_user, error_password, error_verify, email, error_email)
def account_console(): """ The main function that runs the account console. """ # the transactions repository: transactions = [{'d': 1, 't': 'in', 'v': 420, 'des': 'initial_money'}, {'d': 2, 't': 'out', 'v': 90, 'des': 'grocery'}, {'d': 3, 't': 'in', 'v': 80, 'des': 'sp_service'}, {'d': 10, 't': 'out', 'v': 100, 'des': 'cash'}, {'d': 11, 't': 'in', 'v': 200, 'des': 'weed'}, {'d': 13, 't': 'out', 'v': 22, 'des': 'ice_cream'}, {'d': 13, 't': 'in', 'v': 33, 'des': 'luck'}, {'d': 15, 't': 'in', 'v': 420, 'des': 'weed2'}, {'d': 22, 't': 'in', 'v': 222, 'des': 'birthday'}, {'d': 22, 't': 'out', 'v': 100, 'des': 'surprise_motherF'}] numbered_commands = {1: cmd1_add, # add <value> <type> <description> 2: cmd2_insert, # insert <day> <value> <type> <description> 3: cmd3_remove, # remove <day> 4: cmd4_remove, # remove <start day> to <end day> 5: cmd5_remove, # remove <type> 6: cmd6_replace, # replace <day> <type> <description> with <value> 7: cmd7_list, # list 8: cmd8_list, # list <type> 9: cmd9_list, # list [<,=,>] <value> 10: cmd10_list, # list balance <day> 11: cmd11_sum, # sum <type> 12: cmd12_max, # max <type> <day> 13: cmd13_filter, # filter <type> 14: cmd14_filter # filter <type> <value> } TrnStack = [[]] print("\n------------------- COMMAND BASED USER INTERFACE -------------------") print("Type 'info' to learn more about this console.") while True: cmd = input("SCM\Bank Transaction>") try: if cmd == 'exit': exit() elif cmd == 'undo': undo(TrnStack, transactions) elif cmd == 'info': info() else: command = cmd.split() # if the command is correct, validation returns its unique number; otherwise valid sends an exception valid_cmd_nr = valid(command) # if the transactions are about to be modified, append a copy of them to the stack if command[0] in ('add','insert','remove','replace','filter'): TrnStack.append(copy.deepcopy(transactions)) # call the function for the written command by using the command number specified by the validation numbered_commands[valid_cmd_nr](command,transactions) except Exception as ex: print(ex)
def healthcheck(ctx, format, apikey): """\b ------------------------------------------- This command executes a sytem health ckeck. ------------------------------------------- User authorization level: None REST API call: /healthckeck \b ------------------------------------------- NOTE: The function returns the system's health status ("OK" on success / "failed" on failure). ------------------------------------------- """ validation.valid(apikey) ctx.invoke(public_commands.healthcheck, format=format, apikey=apikey)
loss.backward() optimizer.step() distributed.all_reduce(loss_manual_mining.data) losses_manual_mining += loss_manual_mining.data.item() / len( args.devices) if local_rank == 0: total = i + 1 tbar.set_description('epoch: %d, loss manual mining: %.3f' % (epoch + 1, losses_manual_mining / total)) # tbar.set_description('epoch: %d, loss1: %.3f, loss2: %.3f' # % (epoch + 1, losses_manual_mining / (i + 1), losses_hard_mining / (i + 1))) scheduler.step(epoch) if local_rank == 0: checkpoints = { 'score': score_model.module.state_dict(), 'item': image_encoder.state_dict(), 'optimizer': optimizer.state_dict() } torch.save( checkpoints, os.path.join(checkpoints_dir, 'model-epoch{}.pth'.format(epoch + 1))) # score_model.eval() # score_model.eval() with torch.no_grad(): valid(epoch + 1, checkpoints_dir, use_bert=use_bert) distributed.barrier()
boxes = boxes.cuda() optimizer.zero_grad() _, loss_clf, loss_gen = model(features, boxes, obj_len, query) loss_clf = loss_clf.mean() loss_gen = loss_gen.mean() loss = loss_clf + loss_gen loss.backward() optimizer.step() losses_clf += loss_clf.item() losses_gen += loss_gen.item() tbar.set_description('epoch: %d, loss clf: %.3f, loss gen: %.3f' % (epoch + 1, losses_clf / (i + 1), losses_gen / (i + 1))) scheduler.step(epoch) checkpoints = { 'model': model.state_dict(), 'optimizer': optimizer.state_dict() } torch.save( checkpoints, os.path.join(checkpoints_dir, 'model-epoch{}.pth'.format(epoch + 1))) valid(epoch + 1, checkpoints_dir, use_bert=True, large=large) # score_model.eval() # query_embedding.eval() # with torch.no_grad(): # valid(epoch + 1, checkpoints_dir, version=2, use_bert=use_bert)
def Admin(ctx, usermod, username, passw, healthcheck, resetsessions, users, sessionsupd, source, format, apikey, role): """\b ------------------------------------------- System Administration Command ------------------------------------------- User authorization level: Administrator \b ------------------------------------------- Options Usage: ------------------------------------------- \b --usermod --username username --passw password Using this parameter the administrator can create a new user or update an existing user's password. If the username exists, then the passw argument will be the new password of the user. If not, then a new user with the username and password argu- ments will be created. There is an optional parameter --role, where you can declare the role of a new user. \b --healthcheck Using this parameter the administrator can execute a system health check. The function returns the system's health status ("OK" on succes / "failed" on failure). \b --resetsessions Using this parameter the administrator can reset all charging sessions as well as ini- tialize the default admin user (username: admin, password: petrol4ever). NOTE: The reset is final and after the execution of the function, all charging records will be deleted. \b --users username Using this parameter the administrator can see the information of a user. \b --sessionsupd --source filename Using this parameter the administrator can "upload" a CSV file with charging sessions data. The name of the file is stated in the --source argument and the file itself must be in multipart/from-data encoding. \b ------------------------------------------- NOTE: You can call multible function by en- tering more than one option parameters. The options do not have to be in order. \b NOTE: If more than one options are entered, /healthcheck (if called) will be executed first and /resetsessions (if called) last. \b NOTE: Options resetsessions and sessionsupd cannot be executed in the same command. ------------------------------------------- """ upd = validation.validsessionsupd(sessionsupd, source) umod = validation.validusermod(usermod, username, passw) validation.valid(apikey) validation.nand(upd,resetsessions) #Health check if healthcheck: ctx.invoke(public_commands.healthcheck, format=format, apikey=apikey) #User info if users!=None: validation.user() click.echo() click.echo(click.style("Loading user's information...", fg='cyan')) f = open(paths.token_path, "r") token = f.readline() f.close() p = {'format': format, 'apikey': apikey} h = {'Authorization':'Token '+token} service = 'admin/users/'+ users response = requests.get(url=f'{paths.baseURL}/{service}/', headers=h, params=p) if response.status_code == 200: with click.progressbar([1, 2, 3, 4]) as bar: for x in bar: time.sleep(0.4) if format == 'json': res = json.loads(response.text) click.echo() click.echo('User ID: '+ str(res['ID'])) click.echo('Username: '******'Username'])) click.echo('First name: '+ str(res['FirstName'])) click.echo('Last name: '+ str(res['LastName'])) click.echo('Role: '+ str(res['Role'])) click.echo('Date joined: '+ str(res['DateJoined'])) click.echo('Last login: '******'LastLogin'])) else: f = open(paths.temporary_path, 'w') f.write(response.text) f.close() with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: click.echo() click.echo('User ID: '+ str(rows['ID'])) click.echo('Username: '******'Username'])) click.echo('First name: '+ str(rows['FirstName'])) click.echo('Last name: '+ str(rows['LastName'])) click.echo('Role: '+ str(rows['Role'])) click.echo('Date joined: '+ str(rows['DateJoined'])) click.echo('Last login: '******'LastLogin'])) os.remove(paths.temporary_path) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2]) #Password change / New user if umod: f = open(paths.token_path, "r") token = f.readline() f.close() firstname = str(username) lastname = str(username) email = str(username) + '@evmail.com' click.echo('Is this a new user? If so, you may want to enter first name, last name and email. If you' +' do not enter these info they will be automatically filled in. If this is an existing' +' user, then no more changes than password will be applied.') click.echo("Do you want to enter user's info? " + click.style('[y/n]', fg='cyan'), nl=False) c = click.getchar() if c=='y': click.echo() flag = True while flag: firstname = click.prompt('First name') flag = validation.namecheck(firstname) flag = True while flag: lastname = click.prompt('Last name') flag = validation.namecheck(lastname) email = click.prompt('E-mail') click.echo() click.echo() click.echo(click.style("Processing...", fg='cyan')) p = {'format': format, 'role': role, 'firstname': firstname, 'lastname': lastname, 'email': email, 'apikey': apikey} h = {'Authorization':'Token '+token} service = 'admin/usermod/'+ str(username)+ '/'+ str(passw) response = requests.post(url=f'{paths.baseURL}/{service}/', headers=h, params=p) if response.status_code != 401: if format == 'json': res = json.loads(response.text) with click.progressbar([1, 2, 3]) as bar: for x in bar: time.sleep(0.5) if response.status_code == 200: click.echo() click.echo("Usermod status: " + click.style(res['status'], fg='green')) else: click.echo() click.echo("Usermod status: " + click.style(res['status'], fg='red')) else: f = open(paths.temporary_path, 'w') f.write(response.text) f.close() with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: if response.status_code == 200: click.echo() click.echo("Status: " + click.style(rows['status'], fg='green')) else: click.echo() click.echo("Status: " + click.style(rows['status'], fg='red')) os.remove(paths.temporary_path) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2]) #Sessions update if upd: click.echo() click.echo(click.style("Uploading CSV file...", fg='cyan')) ff = open(paths.token_path, "r") token = ff.readline() ff.close() p = {'format': format, 'apikey': apikey} h = {'Authorization':'Token '+token} f = {'file': open(source,'r')} service = 'admin/system/sessionsupd' response = requests.post(url=f'{paths.baseURL}/{service}/', files=f, headers=h, params=p) if response.status_code == 200: if format == 'json': res = json.loads(response.text) with click.progressbar([1, 2, 3, 4, 5]) as bar: for x in bar: time.sleep(0.3) click.echo() click.echo('Sessions in uploaded file: ' + str(res['SessionsInUploadedFile'])) click.echo('Sessions imported: '+ str(res['SessionsImported'])) click.echo('Total sessions in database: '+ str(res['TotalSessionsInDatabase'])) else: f = open(paths.temporary_path, 'w') f.write(response.text) f.close() with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: click.echo() click.echo('Sessions in uploaded file: '+ str(rows['SessionsInUploadedFile'])) click.echo('Sessions imported: '+ str(rows['SessionsImported'])) click.echo('Total sessions in database: '+ str(rows['TotalSessionsInDatabase'])) os.remove(paths.temporary_path) else: click.echo() if response.status_code == 401: if format == 'json': click.echo() raise click.ClickException('Error: Update ' + response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException('Error: Update ' + response.text[4:(len(response.text))-2]) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2]) #Reset sessions if resetsessions: ctx.invoke(public_commands.resetsessions, format=format, apikey=apikey)
def SessionsPerProvider(provider, datefrom, dateto, format, apikey): """\b ------------------------------------------- This command displays all charging sessions from an energy provider, during the givven period of time. ------------------------------------------- User authorization level: Connected user REST API call: /SessionsPerProvider \b ------------------------------------------- NOTE: Date options must be chronologically correct. (--datefrom = starting date , --dateto = ending date) ------------------------------------------- """ validation.valid(apikey) validation.fdatecheck(datefrom) validation.tdatecheck(dateto) validation.chronological(datefrom, dateto) validation.user() click.echo() click.echo(click.style("Loading...", fg='cyan')) f = open(paths.token_path, "r") token = f.readline() f.close() p = {'format': format, 'apikey': apikey} h = {'Authorization':'Token '+token} service = 'SessionsPerProvider/'+ provider+ '/'+ datefrom+ '/'+ dateto with requests.get(url=f'{paths.baseURL}/{service}/', headers=h, params=p, stream=True) as response: if response.status_code == 200 or response.status_code == 402: with click.progressbar([1, 2, 3]) as bar: for x in bar: time.sleep(0.5) if format == 'json': res = json.loads(response.text) click.echo() click.echo('Provider ID: '+ str(res['ProviderID'])) click.echo('Provider name: '+ str(res['ProviderName'])) click.echo('Number of provider charging sessions: '+ str(res['NumberOfProviderChargingSessions'])) if response.status_code == 200: click.echo() click.echo(click.style('Provider Charging Sessions:', fg='cyan')) for session in res['ProviderChargingSessionsList']: click.echo() click.echo('Station ID: '+ str(session['StationID'])) click.echo('Session ID: '+ str(session['SessionID'])) click.echo('Vehicle ID: '+ str(session['VehicleID'])) click.echo('Started on: '+ str(session['StartedOn'])) click.echo('Finished on: '+ str(session['FinishedOn'])) click.echo('Energy delivered: '+ str(session['EnergyDelivered'])+ ' kWh') click.echo('Price policy reform: '+ str(session['PricePolicyRef'])) click.echo('Cost per kWh: '+ str(session['CostPerKWh'])) click.echo('Total cost: '+ str(session['TotalCost'])) else: click.echo() click.echo(click.style('Provider Charging Sessions:', fg='cyan')+ 'No data') else: f = open(paths.temporary_path, 'w') f.write(response.text) f.close() with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: click.echo() click.echo('Provider ID: '+ str(rows['ProviderID'])) click.echo('Provider name: '+ str(rows['ProviderName'])) sessions_count = rows['NumberOfProviderChargingSessions'] sessions_count = int(sessions_count) click.echo('Number of provider charging sessions: '+ str(sessions_count)) if response.status_code == 200: click.echo() click.echo(click.style('Provider Charging Sessions: ', fg='cyan')) for i in range(0,sessions_count): click.echo() click.echo('Station ID: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.StationID'])) click.echo('Session ID: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.SessionID'])) click.echo('Vehicle ID: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.VehicleID'])) click.echo('Started on: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.StartedOn'])) click.echo('Finished on: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.FinishedOn'])) click.echo('Energy delivered: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.EnergyDelivered'])+ ' kWh') click.echo('Price policy reform: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.PricePolicyRef'])) click.echo('Cost per kWh: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.CostPerKWh'])+ ' $') click.echo('Total cost: '+ str(rows['ProviderChargingSessionsList.'+str(i)+'.TotalCost'])+ ' $') else: click.echo() click.echo(click.style('Provider Charging Sessions: ', fg='cyan')+ 'No data') os.remove(paths.temporary_path) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2])
def SessionsPerStation(station, datefrom, dateto, format, apikey): """\b ------------------------------------------- This command displays all charging sessions at a specific station, during the givven pe- riod of time. ------------------------------------------- User authorization level: Connected user REST API call: /SessionsPerStation \b ------------------------------------------- NOTE: Date options must be chronologically correct. (--datefrom = starting date , --dateto = ending date) ------------------------------------------- """ validation.valid(apikey) validation.fdatecheck(datefrom) validation.tdatecheck(dateto) validation.chronological(datefrom, dateto) validation.user() click.echo() click.echo(click.style("Loading...", fg='cyan')) f = open(paths.token_path, "r") token = f.readline() f.close() p = {'format': format, 'apikey': apikey} h = {'Authorization':'Token '+token} service = 'SessionsPerStation/'+ station+ '/'+ datefrom+ '/'+ dateto response = requests.get(url=f'{paths.baseURL}/{service}/', headers=h, params=p) if response.status_code == 200 or response.status_code == 402: with click.progressbar([1, 2, 3]) as bar: for x in bar: time.sleep(0.5) if format == 'json': res = json.loads(response.text) click.echo() click.echo('Station ID: '+ str(res['StationID'])) click.echo('Station operator: '+ str(res['Operator'])) click.echo('Request Timestamp: '+ str(res['RequestTimestamp'])) click.echo('Period from: '+ str(res['PeriodFrom'])) click.echo('Period to: '+ str(res['PeriodTo'])) click.echo('Total energy delivered: '+ str(res['TotalEnergyDelivered'])+ ' kWh') click.echo('Number of charging sessions: '+ str(res['NumberOfChargingSessions'])) click.echo('Number of active points: '+ str(res['NumberOfActivePoints'])) if response.status_code == 200: click.echo() click.echo(click.style('Sessions Summary:', fg='cyan')) for session in res['SessionsSummaryList']: click.echo() click.echo('Point ID: '+ str(session['PointID'])) click.echo('Point sessions: '+ str(session['PointSessions'])) click.echo('Energy delivered: '+ str(session['EnergyDelivered'])+ ' kWh') else: click.echo() click.echo(click.style('Sessions Summary: ', fg='cyan') + 'No data') else: f = open(paths.temporary_path, 'w') f.write(response.text) f.close() with open(paths.temporary_path) as temp: res = csv.DictReader(temp) for rows in res: click.echo() click.echo('Station ID: '+ str(rows['StationID'])) click.echo('Station operator: '+ str(rows['Operator'])) click.echo('Request timestamp: '+ str(rows['RequestTimestamp'])) click.echo('Period from: '+ str(rows['PeriodFrom'])) click.echo('Period to: '+ str(rows['PeriodTo'])) click.echo('Total energy delivered: '+ str(rows['TotalEnergyDelivered'])+ ' kWh') click.echo('Number of charging sessions: '+ str(rows['NumberOfChargingSessions'])) points_count = rows['NumberOfActivePoints'] points_count = int(points_count) click.echo('Number of active points: '+ str(points_count)) if response.status_code == 200: click.echo() click.echo(click.style('Sessions Summary: ', fg='cyan')) for i in range(0,points_count): click.echo() click.echo('Point ID: '+ str(rows['SessionsSummaryList.'+str(i)+'.PointID'])) click.echo('Point sessions: '+ str(rows['SessionsSummaryList.'+str(i)+'.PointSessions'])) click.echo('Energy delivered: '+ str(rows['SessionsSummaryList.'+str(i)+'.EnergyDelivered'])+ ' kWh') else: click.echo() click.echo(click.style('Sessions Summary: ', fg='cyan') + 'No data') os.remove(paths.temporary_path) else: if format == 'json': click.echo() raise click.ClickException(response.text[2:(len(response.text))-2]) else: click.echo() raise click.ClickException(response.text[4:(len(response.text))-2])