Skip to main content

Calculator

Nov 19, 2022CodeCatch
Loading...

More Python Posts

Number guessing game

Nov 19, 2022CodeCatch

0 likes • 0 views

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

Palindrome checker

Nov 19, 2022CodeCatch

0 likes • 3 views

# function which return reverse of a string
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

curry function

Nov 19, 2022CodeCatch

0 likes • 1 view

from functools import partial
def curry(fn, *args):
return partial(fn, *args)
add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) # 30

Convert Decimal to Binary and Hexadecimal

May 31, 2023CodeCatch

0 likes • 0 views

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

Goobla Academy Flask API

Nov 18, 2022AustinLeath

0 likes • 0 views

import os, json, boto3, requests
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
from random import shuffle
app = Flask(__name__)
cors = CORS(app)
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
app.url_map.strict_slashes = False
SECRET_KEY = os.environ.get("SECRET_KEY")
@app.route("/teks")
def teks_request():
teks_file = open("teks.json", "r")
data = json.load(teks_file)
return jsonify(data)
@app.route("/teks/find/113.41.<int:teks_id>.<string:section_id>")
def teks_find_request(teks_id, section_id):
teks_file = open("teks.json", "r")
data = json.load(teks_file)
for item in data:
if item["id"] == teks_id:
for child in item["children"]:
if child["id"] == section_id:
return {"tek": item, "content": child["content"]}
return jsonify(
[
f"Something went wrong. TEKS section id of {section_id} cannot be found within TEKS section {teks_id}."
]
)
@app.route("/lessonplan/read/<id>")
def read_lesson_plan(id):
lesson_table = dynamodb.Table("Lesson_Plans")
items = lesson_table.scan()['Items']
for lesson in items:
if (lesson["uuid"] == id):
return jsonify(lesson)
return {"error": "id does not exist", "section": id}
@app.route("/teks/<int:teks_id>")
def teks_id_request(teks_id):
teks_file = open("teks.json", "r")
data = json.load(teks_file)
for item in data:
if item["id"] == teks_id:
return jsonify(item)
return jsonify([f"Something went wrong. TEKS id of {teks_id} cannot be found."])
@app.route("/assessment/write", methods=["GET", "POST"])
def assessment_write():
assessment_json = request.json
assessment_data = dict(assessment_json)
assessment_table = dynamodb.Table("Assessments")
assessment_table.put_item(Item=assessment_data)
if assessment_data == get_assessment(assessment_data["id"]):
return "Success"
else:
return "Failure"
@app.route("/students/read/<id>")
def students_read(id):
return jsonify(get_students(id))
@app.route("/students/read")
def all_students_read():
student_table = dynamodb.Table("Students")
items = student_table.scan()['Items']
return jsonify(items)
@app.route("/assessment/read/<id>")
def assessment_read(id):
return jsonify(get_assessment(id))
@app.route("/assessment/submit/<id>", methods=["POST"])
def submit_assessment(id):
assessments_table = dynamodb.Table("Assessments")
assessment = assessments_table.get_item(Key={"id": id})
if not assessment.get("Item"):
return {"error": "id does not exist", "section": id}
responses = {
question["id"]: question["response"]
for question in request.json.get("questions")
}
correct_answers = 0
for response in responses:
# print(
# (
# responses[response],
# find_question(assessment.get("Item").get("questions"), response).get(
# "correctAnswer"
# ),
# )
# )
if responses[response] == find_question(
assessment.get("Item").get("questions"), response
).get("correctAnswer"):
correct_answers += 1
score = correct_answers / len(request.json.get("questions"))
users_table = dynamodb.Table("Students")
users_table.update_item(
Key={"uuid": request.json.get("student_id")},
UpdateExpression="SET completedAssessments = list_append(completedAssessments, :i)",
ExpressionAttributeValues={
":i": [
{
"id": id,
"score": round(score * 100),
}
]
},
)
message = None
if round(score * 100) > 70:
message = f"Congratulations! You passed your assessment with a {round(score * 100)}%."
else:
message = f"You failed your assessment with a {round(score * 100)}%."
sns = boto3.client("sns", region_name="us-east-1")
number = "+15125967383"
sns.publish(PhoneNumber=number, Message=message)
return {"score": score, "message": message}
def find_question(all, id):
#print("id to find: ", id)
for question in all:
if question["id"] == id:
#print(question)
return question
def get_assessment(id):
assessment_table = dynamodb.Table("Assessments")
results = assessment_table.get_item(Key={"id": id})
if results.get("Item") is None:
return {"error": "id does not exist", "section": id}
else:
quiz = results.get("Item")
return {
"title": quiz.get("title"),
"id": quiz.get("id"),
"questions": [
{
"id": question.get("id"),
"title": question.get("title"),
"options": random_answers(
question.get("incorrectAnswers")
+ [question.get("correctAnswer")]
),
}
for question in quiz.get("questions")
],
}
def get_students(id):
students_table = dynamodb.Table('Students')
results = students_table.get_item(Key = {
"uuid": id
})
if(results.get("Item") is None):
return {'error': 'id does not exist', 'section': id}
else:
student = results.get("Item")
return student
def lesson_plans_read():
student_table = dynamodb.Table("Lesson_Plans")
items = student_table.scan()['Items']
return jsonify(items)
def random_answers(answers):
shuffle(answers)
return answers
@app.route("/recommendations/<uuid>")
def get_recommendation(uuid):
student_info_table = dynamodb.Table('Students')
lesson_plans_table = dynamodb.Table('Lesson_Plans')
student = get_students(uuid)
tek = student.get("struggleTeks")[0]
lesson_plans = lesson_plans_table.scan( Select='ALL_ATTRIBUTES', FilterExpression='tek = :s', ExpressionAttributeValues={ ":s": tek })
#print(lesson_plans)
return jsonify({"student": student, "lesson_plans": lesson_plans.get("Items")})
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)

guacamole LDAP creation

Nov 18, 2022AustinLeath

0 likes • 0 views

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
def create_guac_connection(BASE_URL, auth_token, ldap_group, computer, guac_group_id):
'''
creates a guac connection
'''
json_header = {'Accept': 'application/json'}
query_parm_payload = { 'token': auth_token }
payload_data = {
"parentIdentifier":guac_group_id,
"name":computer,
"protocol":"vnc",
"parameters":{
"port":"5900",
"read-only":"",
"swap-red-blue":"",
"cursor":"",
"color-depth":"",
"clipboard-encoding":"",
"disable-copy":"",
"disable-paste":"",
"dest-port":"",
"recording-exclude-output":"",
"recording-exclude-mouse":"",
"recording-include-keys":"",
"create-recording-path":"",
"enable-sftp":"true",
"sftp-port":"",
"sftp-server-alive-interval":"",
"enable-audio":"",
"audio-servername":"",
"sftp-directory":"",
"sftp-root-directory":"",
"sftp-passphrase":"",
"sftp-private-key":"",
"sftp-username":"",
"sftp-password":"",
"sftp-host-key":"",
"sftp-hostname":"",
"recording-name":"",
"recording-path":"",
"dest-host":"",
"password":"asdasd",
"username":"asdasd",
"hostname":"nt72310.cvad.unt.edu"
},
"attributes":{
"max-connections":"",
"max-connections-per-user":"1",
"weight":"",
"failover-only":"",
"guacd-port":"",
"guacd-encryption":"",
"guacd-hostname":""
}
}
CREATE_CONNECTION_URL = BASE_URL + "/api/session/data/mysql/connections"
create_connection_request = requests.post(CREATE_CONNECTION_URL, headers=json_header, params=query_parm_payload, data=payload_data, verify=False)
create_connection_result = create_connection_request.status_code
if create_connection_result == "200":
print("Successfully created computer: " + computer)
else:
print(create_connection_request.json())
return create_connection_result