Selection sort
0 likes • Nov 19, 2022
Python
Loading...
More Python Posts
import osimport sysimport argparseimport jsonimport csvimport getpassimport stringimport randomimport refrom datetime import datetimeimport ldapimport requestsfrom requests.packages.urllib3.exceptions import InsecureRequestWarningrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)from requests.auth import HTTPBasicAuthimport validatorsimport ipdb# ldap functionsdef get_ldap_group_members(ldap_group, user, passwrd, DOMAIN, DOMAIN_SEARCH_BASE):#DOMAIN_GROUP, DOMAIN_USER, DOMAIN_PASS, DOMAIN, DOMAIN_SEARCH_BASE'''Input a user name and search the directory'''#---- Setting up the Connection#account used for binding - Avoid putting these in version controlbindDN = str(user)bindPass = passwrd#set some tuneables for the LDAP library.ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW)#ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, CACERTFILE)conn = ldap.initialize('ldaps://'+str(DOMAIN))conn.protocol_version = 3conn.set_option(ldap.OPT_REFERRALS, 0)#authenticate the connection so that you can make additional queriestry:result = conn.simple_bind_s(bindDN, bindPass)except ldap.INVALID_CREDENTIALS:result = "Invalid credentials for %s" % usersys.exit()#build query in the form of (uid=user)ldap_query = '(cn=' + ldap_group + ')'query_result = []lencount = Truerange_start = 0total_active_students_count = 0while lencount:#print(len(query_result))range_end = range_start + 1499member_range = ['member;range=' + str(range_start) + '-' + str(range_end)]#print(member_range)ldap_info = conn.search_s(str(DOMAIN_SEARCH_BASE), ldap.SCOPE_SUBTREE, filterstr=ldap_query, attrlist=member_range)member_range = next(iter(ldap_info[0][1].keys()))ldap_objects = ldap_info[0][1][member_range]print("\n")for ldap_object in ldap_objects:decoded_member_string = ldap_object.decode("utf-8")member_cn = re.split('=|,', decoded_member_string)[1]print(f"User number: {total_active_students_count} in {ldap_group}: {member_cn}")query_result.append(member_cn)total_active_students_count = total_active_students_count + 1if len(ldap_objects) == 1500:lencount = Truerange_start += 1500range_end += 1500else:lencount = Falseprint(f"TOTAL USERS IN ActiveStudents: {total_active_students_count}")return query_resultdef main():user = input("Enter a UNT bind username: ") + "@students.ad.unt.edu"passwrd = getpass.getpass(prompt='Enter UNT bind password: ', stream=None)get_ldap_group_members("ActiveStudents", user, passwrd, "students.ad.unt.edu", "DC=students,DC=ad,DC=unt,DC=edu")if __name__ == "__main__":main()
""" Number Guessing Game----------------------------------------"""import randomattempts_list = []def show_score():if len(attempts_list) <= 0:print("There is currently no high score, it's yours for the taking!")else:print("The current high score is {} attempts".format(min(attempts_list)))def start_game():random_number = int(random.randint(1, 10))print("Hello traveler! Welcome to the game of guesses!")player_name = input("What is your name? ")wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))// Where the show_score function USED to beattempts = 0show_score()while wanna_play.lower() == "yes":try:guess = input("Pick a number between 1 and 10 ")if int(guess) < 1 or int(guess) > 10:raise ValueError("Please guess a number within the given range")if int(guess) == random_number:print("Nice! You got it!")attempts += 1attempts_list.append(attempts)print("It took you {} attempts".format(attempts))play_again = input("Would you like to play again? (Enter Yes/No) ")attempts = 0show_score()random_number = int(random.randint(1, 10))if play_again.lower() == "no":print("That's cool, have a good one!")breakelif int(guess) > random_number:print("It's lower")attempts += 1elif int(guess) < random_number:print("It's higher")attempts += 1except ValueError as err:print("Oh no!, that is not a valid value. Try again...")print("({})".format(err))else:print("That's cool, have a good one!")if __name__ == '__main__':start_game()
import itertoolsimport stringimport timedef guess_password(real):chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuationattempts = 0for password_length in range(1, 9):for guess in itertools.product(chars, repeat=password_length):startTime = time.time()attempts += 1guess = ''.join(guess)if guess == real:return 'password is {}. found in {} guesses.'.format(guess, attempts)loopTime = (time.time() - startTime);print(guess, attempts, loopTime)print("\nIt will take A REALLY LONG TIME to crack a long password. Try this out with a 3 or 4 letter password and see how this program works.\n")val = input("Enter a password you want to crack that is 9 characters or below: ")print(guess_password(val.lower()))
# Deleting all even numbers from a lista = [1,2,3,4,5]del a[1::2]print(a)
# Prompt user for a decimal numberdecimal = int(input("Enter a decimal number: "))# Convert decimal to binarybinary = bin(decimal)# Convert decimal to hexadecimalhexadecimal = hex(decimal)# Display the resultsprint("Binary:", binary)print("Hexadecimal:", hexadecimal)
#Python program to print topological sorting of a DAGfrom collections import defaultdict#Class to represent a graphclass Graph:def __init__(self,vertices):self.graph = defaultdict(list) #dictionary containing adjacency Listself.V = vertices #No. of vertices# function to add an edge to graphdef addEdge(self,u,v):self.graph[u].append(v)# A recursive function used by topologicalSortdef topologicalSortUtil(self,v,visited,stack):# Mark the current node as visited.visited[v] = True# Recur for all the vertices adjacent to this vertexfor i in self.graph[v]:if visited[i] == False:self.topologicalSortUtil(i,visited,stack)# Push current vertex to stack which stores resultstack.insert(0,v)# The function to do Topological Sort. It uses recursive# topologicalSortUtil()def topologicalSort(self):# Mark all the vertices as not visitedvisited = [False]*self.Vstack =[]# Call the recursive helper function to store Topological# Sort starting from all vertices one by onefor i in range(self.V):if visited[i] == False:self.topologicalSortUtil(i,visited,stack)# Print contents of stackprint(stack)g= Graph(6)g.addEdge(5, 2);g.addEdge(5, 0);g.addEdge(4, 0);g.addEdge(4, 1);g.addEdge(2, 3);g.addEdge(3, 1);print("Following is a Topological Sort of the given graph")g.topologicalSort()