Skip to main content

Selection sort

0 likes • Nov 19, 2022
Python
Loading...
Download

More Python Posts

Query UNT ActiveStudents

AustinLeath
0 likes • Nov 18, 2022
Python
import os
import sys
import argparse
import json
import csv
import getpass
import string
import random
import re
from datetime import datetime
import ldap
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from requests.auth import HTTPBasicAuth
import validators
import ipdb
# ldap functions
def 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 control
bindDN = 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 = 3
conn.set_option(ldap.OPT_REFERRALS, 0)
#authenticate the connection so that you can make additional queries
try:
result = conn.simple_bind_s(bindDN, bindPass)
except ldap.INVALID_CREDENTIALS:
result = "Invalid credentials for %s" % user
sys.exit()
#build query in the form of (uid=user)
ldap_query = '(cn=' + ldap_group + ')'
query_result = []
lencount = True
range_start = 0
total_active_students_count = 0
while lencount:
#print(len(query_result))
range_end = range_start + 1499
member_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 + 1
if len(ldap_objects) == 1500:
lencount = True
range_start += 1500
range_end += 1500
else:
lencount = False
print(f"TOTAL USERS IN ActiveStudents: {total_active_students_count}")
return query_result
def 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

CodeCatch
0 likes • Nov 19, 2022
Python
""" Number Guessing Game
----------------------------------------
"""
import random
attempts_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 be
attempts = 0
show_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 += 1
attempts_list.append(attempts)
print("It took you {} attempts".format(attempts))
play_again = input("Would you like to play again? (Enter Yes/No) ")
attempts = 0
show_score()
random_number = int(random.randint(1, 10))
if play_again.lower() == "no":
print("That's cool, have a good one!")
break
elif int(guess) > random_number:
print("It's lower")
attempts += 1
elif int(guess) < random_number:
print("It's higher")
attempts += 1
except 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()

bruteforce password cracker

AustinLeath
0 likes • Nov 18, 2022
Python
import itertools
import string
import time
def guess_password(real):
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation
attempts = 0
for password_length in range(1, 9):
for guess in itertools.product(chars, repeat=password_length):
startTime = time.time()
attempts += 1
guess = ''.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()))

Delete all even numbers

CodeCatch
0 likes • Nov 19, 2022
Python
# Deleting all even numbers from a list
a = [1,2,3,4,5]
del a[1::2]
print(a)
# Prompt user for a decimal number
decimal = int(input("Enter a decimal number: "))
# Convert decimal to binary
binary = bin(decimal)
# Convert decimal to hexadecimal
hexadecimal = hex(decimal)
# Display the results
print("Binary:", binary)
print("Hexadecimal:", hexadecimal)

Topological sort

CodeCatch
0 likes • Nov 19, 2022
Python
#Python program to print topological sorting of a DAG
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# A recursive function used by topologicalSort
def topologicalSortUtil(self,v,visited,stack):
# Mark the current node as visited.
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
# Push current vertex to stack which stores result
stack.insert(0,v)
# The function to do Topological Sort. It uses recursive
# topologicalSortUtil()
def topologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
stack =[]
# Call the recursive helper function to store Topological
# Sort starting from all vertices one by one
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
# Print contents of stack
print(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()