def create_profile(path: str): """ :param path: :return: """ assert type(path) is str, 'path needs to be str' # get the users data dsuserver = input('DSU server (type it directly without quotation marks): ') username = input('username: '******'password: '******'post (optional, skip by pressing enter): ') post.set_entry(entry) bio = input('bio (optional, skip by pressing enter): ') # create the profile and pass data in profile = Profile.Profile(dsuserver, username, password) profile.bio = bio profile.add_post(post) profile.save_profile(path) print('DSU file storing...') print("Local file stored at: " + str(path)) # ask if the user wants to upload upload_option(profile)
def formProfile(Motifs): listARG = [] count = [] Profile = [] allcount = [] for i in range(len(Motifs[0])): Profile.append([]) for j in range(4): Profile[i].append(0) for i in range(len(Motifs[0])): count.append([1, 1, 1, 1]) for i in range(len(Motifs)): for j in range(len(Motifs[i])): if Motifs[i][j] == 'A': count[j][0] += 1 if Motifs[i][j] == 'C': count[j][1] += 1 if Motifs[i][j] == 'G': count[j][2] += 1 if Motifs[i][j] == 'T': count[j][3] += 1 for i in range(len(Motifs[0])): allcount.append(0) for j in range(4): allcount[i] += count[i][j] for j in range(4): Profile[i][j] = count[i][j] * 1.0 / allcount[i] listARG.append(Profile) listARG.append(allcount) return listARG
def create_person(transactions_list, location): # list of restaurant transactions newProfile = Profile() tot_spend = 0 num_restaurant_transactions = 0 favorites = {} prices = [] for transaction in transactions_list: newProfile.totalSpent += transaction[u'amount'] prices.append(transaction[u'amount']) category_scores = {} newProfile.transactions = transactions_list #Putting duplicate transactions into favorites for rest in newProfile.transactions: if rest[u'name'] in favorites: favorites[rest[u'name']] += 1 else: favorites[rest['name']] = 1 for tag in rest[u'category']: # update to skew towards recent transactions if tag in category_scores: category_scores[tag] += 1 else: category_scores[tag] = 1 prices.sort() # newProfile.medianSpending = statistics.median(prices) avgspend = newProfile.totalSpent / len(newProfile.transactions) newProfile.favorites = reversed([ x for x in sorted(newProfile.favorites.items(), key=lambda kv: kv[1]) ]) newProfile.category_scores = category_scores return newProfile
def promptUser(): ans = input("Load profile (L) or create new (N)? ") if ans.upper() == 'L': return Profile.loadProfile() elif ans.upper() == 'N': return Profile.createProfile() else: print('Invalid input!') promptUser()
def command_R(commands): """ Functionalities within command R, print the content of a DSU file. :param commands: the input command :return: None """ if len(commands) < 2: print('ERROR') elif len(commands) == 2: path = Path(commands[1]) if not str(path).endswith('.dsu'): print('ERROR') else: with open(str(path), 'r') as f: if path.stat().st_size == 0: print('EMPTY') else: output = f.readlines() for i in range(len(output)): if i == len(output) - 1: # should not print a newline at the end print(output[i], end='') else: print(output[i]) # -l option to load elif len(commands) == 3 and commands[2] == '-l': profile = Profile.Profile() profile.load_profile(commands[1]) display_profile(profile) upload_option(profile) else: raise Exception('ERROR')
def upload_option(profile: Profile): """ The interface to upload profile to server, working with ds_client module's send(). :param profile: current working profile object :return: None """ option = input("Do you want to also upload it to the server? (y/n)\n").upper() server = profile.dsuserver username = profile.username password = profile.password message = profile.get_posts() bio = profile.bio if option == 'Y': print("Send post (p)") print("Update bio (b)") print("Send post and update bio (pb)") option = input() client.send(option, server, PORT, username, password, message, bio) elif option == 'N': print("Done.") else: print('please enter either y or n\n') upload_option(profile)
def main(): print("ok") dic = { 'Model_0': { 'delta': { 'src_eid_0': 1, 'src_eid_1': 2 } }, 'Model_1': { 'delta': { 'src_eid_1': 42 } } } #step(dic) START = '2014-01-01 00:00:00' date = datetime(2014, 1, 1, 0, 0, 0, 0) print(date) i = 3 date2 = date + timedelta(minutes=(1 * i)) print("ok") print(date2) prof = Profile.Profile(1, 24, 0) print("Debut export") prof.exportCSV(START_DATE=date, step_size=60, filename="profile.csv", modelname='ModelProfil') print("Fin export")
def borda_count( matrix: Preference_Matrix.Preference_Matrix) -> Profile.Profile: result: Profile.Profile = Profile.Profile() result.initialize(matrix[0]) return result
def steer (filename): """Given an input page and role, return a destination""" page = __get_page_name (filename) user = Auth.get_user() roles = Role.get_user_roles () request = CTK.request.url params = request.split('/')[-1] profile_name = '__default__' profile_id = user.get('profile_id') user_id = user.get('id') user_name = user.get('username') profiles = Profile.get_profiles () for x in profiles: if x['id'] == profile_id: profile_name = x['name'] break entry = Workflow.SCRIPT[page] if profile_name in entry: destination = entry[profile_name] % locals() else: destination = entry['__default__'] % locals() return CTK.HTTP_Redir (destination)
def test1(): matrix: Preference_Matrix.Preference_Matrix = Preference_Matrix.Preference_Matrix( ) matrix.set_matrix(5, 5) print("\n") matrix.print() print("\n") rank: Social_Choice_Rank.Rank = Social_Choice_Rank.Rank() rank.generate_ranking(matrix) print(rank) print("\n") profile: Profile.Profile = Profile.Profile() profile = qualified_majority(matrix) matrix.print() print("\n") print(profile) print("\nThe winner is: " + str(profile.winner()))
def mainBrain(): print(""" Welcome to BestBuy Product Checker Version: 1.01 -------------------------------------- """) print('Profiles\n________\n') userProfile = Profile.check_If_Files_Exist() print(userProfile) clear() userStoreList = LocationFinder.mainBrain() storeNums = [] try: for stores in userStoreList: for store in stores: storeNum = store.split("-")[1].replace(" ", '').replace(")", '') storeNums.append(storeNum) LoopRunner(storeNums, userProfile) except: for store in userStoreList: storeNum = store.split("-")[1].replace(" ", '').replace(")", '') storeNums.append(storeNum) LoopRunner(storeNums, userProfile) print('Profile file was not setup correctly') mainBrain()
def profile(request: Request) -> ProfileResponse: """Get a profile.""" profile = object_or_404( Profile.by_username( request.openapi_validated.parameters["path"]["username"], db=request.db ) ) return {"profile": profile}
def Add_Empty_Profile(self, target): """Add a profile given just a name""" if (self.Is_Profile(target) == 1): return else: p = Profile.Profile(target) self.profile_list.append(p) self.display.Add_Profile(target)
def c13(): input = "foo=bar&baz=qux&zap=zazzle" #print Profile.parse(input) input2 = "*****@*****.**" p = Profile.profile_for(input2) # print p , p.encode() # now we make role= appear at the end of a block legit_email = "*****@*****.**" lp = Profile.profile_for(legit_email) legit_ciphertext = Profile.encrypt(lp.encode()) # generate a fake profile where 'admin' appears at the begining of a block fake_email = "A"*10 + "admin" fp = Profile.profile_for(fake_email) fake_ciphertext = Profile.encrypt(fp.encode()) # perform a cut and paste of the ECB ciphertexts obtained above ciphertext = legit_ciphertext[:32] + fake_ciphertext[16:32] # fake_profile = Profile.decrypt(ciphertext) # print fake_profile new_profile = Profile.parse(Profile.decrypt(ciphertext)) print new_profile
def do_load(self, line): filename, register = getArgs(line) try: profile = Profile.Profiler(filename) except FileNotFoundError: print("Failed open file %s" % filename) else: print("Load profile file %s into register %s" % (filename, register)) self.profiles[register] = profile
def Exclude(self): name_hopeful = self.entry_new.get() if (self.Name_Preexists(name_hopeful) == 1): return #failed new_term = Profile.Term(name_hopeful, "Exclude") self.profile_list.append(new_term) #append to profile_list dl = self.Make_Display_List(self.profile_list) #update display box self.profile.setlist(dl) return
def simple_majority( matrix: Preference_Matrix.Preference_Matrix) -> Profile.Profile: result: Profile.Profile = Profile.Profile() result.initialize(matrix[0]) rank: Social_Choice_Rank.Rank = Social_Choice_Rank.Rank() rank.generate_ranking(matrix) return result
def list_posts(profile: Profile): """ Print out the posts in a profile object. :param profile: current working profile object :return: None """ print("Here are your posts:") posts = profile.get_posts() for i in range(len(posts)): print("Entry {}:".format(str(i)), posts[i].get_entry())
def __init__(self, row: int = None, column: int = None, mtx: [Profile.Profile] = None): self.rowsize: int = row if row is not None else 0 self.columnsize: int = column if column is not None else 0 self.matrix: list(Profile.Profile( )) = mtx if mtx is not None else list() # Modified this. TESTING
def NewProfileOp(self, e): sketches = self.GetSelectedSketches() sketch = 0 if len(sketches) > 0: sketch = sketches[0] new_object = Profile.Profile(sketch) new_object.ReadDefaultValues() new_object.SetID(cad.GetNextID(Profile.type)) new_object.AddMissingChildren() # add the tags container self.EditAndAddSketchOp(new_object, sketches)
def save_profile(): first_name = request.form['fName'] last_name = request.form['lName'] date = request.form['date'] password = request.form['password'] phone = request.form['phone'] address = request.form['address'] profile_to_write = Profile.Profile(first_name, last_name, date, password, phone, address) f = open("/tmp/profile.pickle","w") pickle.dump(profile_to_write, f) return redirect("/profile")
def create_user_for_profile(profile: Profile, user_data: UserData) -> None: username = user_data['username'].strip() if is_username_duplicate(username): raise ValidationError('Username is duplicate') email = user_data['email'].strip() if is_user_email_duplicate(email): raise ValidationError('Email is duplicate') user = User( username=username, email=email, ) password = user_data['password'] user.set_password(password) user.save() profile.user = user profile.save()
def callback(): nname, npassw, ndob = n.get().strip(), p.get().strip(), Dob.get( ).strip() if nname == '' or any(str.isdigit(x) for x in nname): import ErrorName top.destroy() import Edit Edit.run(usn, name, dob, passw) date = ndob.split('/') #print len(ndob) if len(ndob) != 10: import ErrorDOB top.destroy() import Edit Edit.run(usn, name, dob, passw) if len(date) != 3: import ErrorDOB top.destroy() import Edit Edit.run(usn, name, dob, passw) if not (int(date[0]) in range(1, 32) or date[1] in range(1, 13) or int((datetime.now().year) - int(date[1])) < 13): import ErrorDOB top.destroy() import Edit Edit.run(usn, name, dob, passw) path = "C:\\" path += usn x = path[2] path += x path1 = path + usn + '.dat' #os.remove(path1) fw1 = open(path1, "wb") fw1.write(npassw + '\n') fw1.write(ndob + '\n') fw1.write(nname + '\n') fw1.write(usn) fw1.close() top.destroy() import Profile Profile.run(usn)
def New_Profile(self, name, term_list=[]): """Create a new profile given a name and a term list""" if (name == '' or name == GUI.root_profile_name): return 0 if (self.Is_Profile(name)): return 0 #at this point name is valid p = Profile.Profile(name, self.counter) self.counter = self.counter + 1 self.profile_list.append(p) p.term_list = term_list self.Apply_Profile_Term_List(p) self.display.Add_Profile(name) return 1
def formProfile(Motifs): count = [] Profile = [] for i in range(len(Motifs[0])): Profile.append([]) for j in range(4): Profile[i].append(0) for i in range(len(Motifs[0])): count.append([0, 0, 0, 0]) for i in range(len(Motifs)): for j in range(len(Motifs[i])): if Motifs[i][j] == 'A': count[j][0] += 1 if Motifs[i][j] == 'C': count[j][1] += 1 if Motifs[i][j] == 'G': count[j][2] += 1 if Motifs[i][j] == 'T': count[j][3] += 1 for i in range(len(Motifs[0])): for j in range(4): Profile[i][j] = count[i][j] * 1.0 / len(Motifs) return Profile
def edit_user(): # Authentication is_admin = Role.user_has_role(Role.ROLE_ADMIN) user_id = CTK.request.url.split('/')[3] profile_id = Profile.get_user_profile(user_id) current_id = Auth.get_user_id() try: is_self = (int(user_id) == current_id) except: is_self = False if not is_admin and not is_self: return CTK.HTTP_Redir('/') user_query = "SELECT * FROM users WHERE id = '%(user_id)s';" % (locals()) profile_query = "SELECT id, description FROM profiles;" # Table table = PropsAutoSQL('/admin/user/apply', user_query) table.AddConstant('userid', user_id) table.AddConstant('old_password', table.SQL_result['password'][0]) if is_admin: props = {} if int(current_id) == int(user_id): props['disabled'] = '' props['selected'] = profile_id profiles = ComboboxSQL(props, profile_query) table.Add('Profile', profiles, 'profile_id', 'Profile del usuario') table.Add('Login', CTK.TextField({'disabled': True}), 'username', 'Login de usuario') table.Add('Password', CTK.TextFieldPassword(), 'password', 'Clave de acceso') table.Add('Nombre', CTK.TextField(), 'forename', 'Nombre propio') table.Add('Apellido 1', CTK.TextField(), 'surname1', 'Primer Apellido') table.Add('Apellido 2', CTK.TextField(), 'surname2', 'Segundo Apellido') table.Add('E-Mail', CTK.TextField(), 'email', 'Cuenta de correo electronico') page = Page.Default() if is_admin: title = '%s: %s' % (ADMIN_LINK, LINK_HREF % (LOCATION, 'Usuarios')) else: title = '%s Edición de usuario' % BACK_LINK page += CTK.RawHTML("<h1>%s</h1>" % title) page += table return page.Render()
def RANDOM(DNA, k, mProfile): m = [] nm = [] c = 0 for i in range(len(DNA) - k + 1): m.append(Profile.countProbably(DNA, i, k, mProfile)) c += m[-1] for i in range(len(DNA) - k + 1): m[i] /= c p = random.randint(0, 10e13 - 1) sum = -1 i = 0 while sum < p: sum += int(m[i] * 10e13) i += 1 return i - 1
def test_json_renderer(db: Session, democontent: None) -> None: """Test that Profile is correctly rendered for an OpenAPI JSON response.""" user = User.by_username("one", db=db) request = DummyRequest() request.user = user profile = Profile(user=user) # type: ignore renderer = json_renderer() output = renderer(None)(profile, {"request": request}) assert json.loads(output) == { "username": "******", "bio": None, "image": None, }
def __init__(self, param=Parameters): self.genotype = [] self.fitness = float("inf") self.violations = float("inf") self.socialFitness = float(0) self.totalFitness = float(0) self.restrictions = [] #generating optimization parameters for i in range(0, param.dim): self.genotype.append( random.uniform(param.lowBound[i], param.uppBound[i])) #generating strategy profile self.profile = Profile.Profile(param) Gene.population += 1
def edit_user(): # Authentication is_admin = Role.user_has_role (Role.ROLE_ADMIN) user_id = CTK.request.url.split('/')[3] profile_id = Profile.get_user_profile (user_id) current_id = Auth.get_user_id() try: is_self = (int(user_id) == current_id) except: is_self = False if not is_admin and not is_self: return CTK.HTTP_Redir('/') user_query = "SELECT * FROM users WHERE id = '%(user_id)s';" %(locals()) profile_query = "SELECT id, description FROM profiles;" # Table table = PropsAutoSQL ('/admin/user/apply', user_query) table.AddConstant ('userid', user_id) table.AddConstant ('old_password', table.SQL_result['password'][0]) if is_admin: props = {} if int(current_id) == int(user_id): props['disabled'] = '' props['selected'] = profile_id profiles = ComboboxSQL (props, profile_query) table.Add ('Profile',profiles, 'profile_id', 'Profile del usuario') table.Add ('Login', CTK.TextField({'disabled':True}), 'username', 'Login de usuario') table.Add ('Password', CTK.TextFieldPassword(), 'password', 'Clave de acceso') table.Add ('Nombre', CTK.TextField(), 'forename', 'Nombre propio') table.Add ('Apellido 1', CTK.TextField(), 'surname1', 'Primer Apellido') table.Add ('Apellido 2', CTK.TextField(), 'surname2', 'Segundo Apellido') table.Add ('E-Mail', CTK.TextField(), 'email', 'Cuenta de correo electronico') page = Page.Default() if is_admin: title = '%s: %s' % (ADMIN_LINK, LINK_HREF % (LOCATION, 'Usuarios')) else: title = '%s Edición de usuario' % BACK_LINK page += CTK.RawHTML ("<h1>%s</h1>" % title) page += table return page.Render()
def load_profile_from_database(self, profile_name): profile = Profile(profile_name) liked_profile = self.load_liked_recipes_from_profile2(profile_name) profile.set_liked_recipes(liked_profile) disliked_profile = self.load_disliked_recipes_from_profile2( profile_name) profile.set_disliked_recipes(disliked_profile) return profile
def qualified_majority( matrix: Preference_Matrix.Preference_Matrix) -> Profile.Profile: result: Profile.Profile = Profile.Profile() result.initialize(matrix[0].alternatives) rank: Social_Choice_Rank.Rank = Social_Choice_Rank.Rank() rank.generate_ranking(matrix) # The error is here. Ranking miscreated # The miscounting problem occurs because of ival in rank for opt in result: for pair in rank: # If x.value > y.value if pair[2] > pair[3]: # If opt == x if opt.get_opt() == pair[0]: opt._value += 1 else: continue # Else, if x.value < y.value elif pair[2] < pair[3]: # If opt == y if opt.get_opt() == pair[1]: opt._value += 1 else: continue elif pair[2] == pair[3]: continue result.order_by_value() return result
def c13_enhanced(): """ In this enhanced mode of c13, we search for the appropriate sizes of the legitimate, fake profile's. i denotes the size of the legitimate email id that is created so that the word role= is positioned at the end of a block j denotes the size of the fake email id that we create to position admin at the begining of a new block since we do not know whether the keywordsd role=, admin are part fo the cookie, we search for all possible pairs i,j and perform the ECB cut and paste attack performed in part 13 for one combiantion of i,j the keyword role= would be at the end of a block and the fake profile's 'admin' would be at the begining of a block. splicing the two and decrypting, generates a counterfeit profile with its privilege escalated """ input = "foo=bar&baz=qux&zap=zazzle" #print Profile.parse(input) input2 = "*****@*****.**" p = Profile.profile_for(input2) # now we make 'role='' appear at the end of a block # since we do not know where eactly it occurs in the plaintext, we # search for all possible sizes for the email id such that 'role=' would # be pushed to the end of a block bsize = 16 for i in range(bsize): legit_email = "a"*i + "@bar.com" lp = Profile.profile_for(legit_email) legit_ciphertext = Profile.encrypt(lp.encode()) # generate a fake profile where 'admin' appears at the begining of a block # search all possible sizes from 0 through bsize, so that 'admin' falls # at the begining of a block for j in range(bsize): fake_email = "A"*j + "admin" fp = Profile.profile_for(fake_email) fake_ciphertext = Profile.encrypt(fp.encode()) # perform a cut and paste of the ECB ciphertexts obtained above ciphertext = legit_ciphertext[:32] + fake_ciphertext[16:32] # print fake_profile new_profile = Profile.parse(Profile.decrypt(ciphertext)) print new_profile , i , j, "\n"
def test(): # Base vars rawdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "raw") path = os.path.join(rawdir, "keyfunc") with open(path, "rb") as fr: data = fr.read() datalen = len(data) nsProf = Profile(path, 0x5000, 0x500000, 0x1000, 0x700000, 0x50000) # Emulate code res = Emulator().emulateKeyFunc(nsProf, 0x44018, datalen / 4 - 1) # Display resulting data Util().dumpData(res, nsProf._heapstart, nsProf._tls)
def set_matrix( self, row: int, column: int): # Remember to deal with cases where column >= 26 self.rowsize = row self.columnsize = column alphabet: [str] = [chr(i) for i in range(ord('a'), ord('z') + 1)] for i in range(row): setofalts: Profile.Profile = Profile.Profile( ) # had to do this so as to create new/different objects, since python passes by reference setofalts.reserve(column) self.matrix.append(setofalts) randlist: [int] = self.__shuffle_values(column) for j in range(column): self.matrix[i][j] = Options.Options( alphabet[j], False, randlist[j] ) # Modified: added Options.Options() -> This solved the issues
# How to use Profile.py # # ############################################################################### # Use Profule.py import Profile as P ############################################################################### # Ribeira #tanP 0.03 | xP 0.85 | zB 3.1 | tanB 0.06 #read profile file in .npy format A = P.Profile('profile_testSet_RI_20091023.npy', platform_slope=0.03, y_rocky_coastline=0.85) # plot the profile A.plot() #calculate volume of sandybeach A.sandy_volArea(platform_slope=0.03, y_rocky_coastline=0.85, lower_bound=-2, right_bound=90, upper_bound=5) #plot calculated volume A.plot_volumeArea()