Skip to main content

print indices

0 likes • Nov 18, 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()

Print "X" pattern

CodeCatch
0 likes • Nov 19, 2022
Python
def print_x_pattern(size):
i,j = 0,size - 1
while j >= 0 and i < size:
initial_spaces = ' '*min(i,j)
middle_spaces = ' '*(abs(i - j) - 1)
final_spaces = ' '*(size - 1 - max(i,j))
if j == i:
print(initial_spaces + '*' + final_spaces)
else:
print(initial_spaces + '*' + middle_spaces + '*' + final_spaces)
i += 1
j -= 1
print_x_pattern(7)

Calculate Square Root

AustinLeath
0 likes • Nov 18, 2022
Python
# Python Program to calculate the square root
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))

Calculate the Area of a Triangle

CodeCatch
0 likes • May 31, 2023
Python
# Prompt user for base and height
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
# Calculate the area
area = (base * height) / 2
# Display the result
print("The area of the triangle is:", area)

AnyTree Randomizer

NoahEaton
0 likes • Apr 15, 2021
Python
import anytree as at
import random as rm
# Generate a tree with node_count many nodes. Each has a number key that shows when it was made and a randomly selected color, red or white.
def random_tree(node_count):
# Generates the list of nodes
nodes = []
for i in range(node_count):
test = rm.randint(1,2)
if test == 1:
nodes.append(at.Node(str(i),color="white"))
else:
nodes.append(at.Node(str(i),color="red"))
#Creates the various main branches
for i in range(node_count):
for j in range(i, len(nodes)):
test = rm.randint(1,len(nodes))
if test == 1 and nodes[j].parent == None and (not nodes[i] == nodes[j]):
nodes[j].parent = nodes[i]
#Collects all the main branches into a single tree with the first node being the root
for i in range(1, node_count):
if nodes[i].parent == None and (not nodes[i] == nodes[0]):
nodes[i].parent = nodes[0]
return nodes[0]

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()