Skip to main content

Find URL in string

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

More Python Posts

bruteforce password cracker

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

Goobla Academy Flask API

0 likes • Nov 18, 2022 • 0 views
Python
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)

Propositional logic with itertools

0 likes • Nov 18, 2022 • 0 views
Python
from itertools import product
V='∀'
E='∃'
def tt(f,n) :
xss=product((0,1),repeat=n)
print('function:',f.__name__)
for xs in xss : print(*xs,':',int(f(*xs)))
print('')
# p \/ (q /\ r) = (p \/ q) /\ (p \/ r)
def prob1(p,q,r) :
x=p or (q and r)
y= (p or q) and (p or r)
return x==y
tt(prob1,3)
# p/\(q\/r)=(p/\q)\/(p/\r)
def prob2(p,q,r) :
x=p and ( q or r )
y=(p and q) or (p and r)
return x==y
tt(prob2,3)
#~(p/\q)=(~p\/~q)
def prob3(p,q) :
x=not (p and q)
y=(not p) or (not q)
return x==y
tt(prob3,2)
#(~(p\/q))=((~p)/\~q)
def prob4(p, q):
x = not(p or q)
y = not p and not q
return x == y
tt(prob4, 2)
#(p/\(p=>q)=>q)
def prob5(p,q):
x= p and ( not p or q)
return not x or q
tt(prob5,2)
# (p=>q)=((p\/q)=q)
def prob6(p,q) :
x = (not p or q)
y=((p or q) == q)
return x==y
tt(prob6,2)
#((p=>q)=(p\/q))=q
def prob7(p,q):
if ((not p or q)==(p or q))==q:
return 1
tt(prob7,2)
#(p=>q)=((p/\q)=p)
def prob8(p,q):
if (not p or q)==((p and q)==p):
return 1
tt(prob8,2)
#((p=>q)=(p/\q))=p
def prob9(p,q):
if ((not p or q)==(p and q))==p:
return '1'
tt(prob9,2)
#(p=>q)/\(q=>r)=>(p=>r)
def prob10(p,q,r) :
x = not ((not p or q) and (not q or r)) or (not p or r)
return x
tt(prob10, 3)
# (p = q) /\ (q => r) => (p => r)
#answer 1
def prob11(p,q,r) :
x = not((p is q) and (not q or r)) or (not p or r)
return x
tt(prob11, 3)
#(p=q)/\(q=>r)=>(p=>r)
#answer 2
def prob11(p,q,r):
x=(p==q) and (not q or r)
y=not p or r
return not x or y
tt(prob11,3)
#((p=>q)/\(q=r))=>(p=>r)
def prob12(p,q,r):
x=(not p or q) and ( q==r )
y=not p or r
return not x or y
tt(prob12,3)
#(p=>q)=>((p/\r)=>(q/\r))
def prob13(p,q,r):
x=not p or q
y=(not(p and r) or ( q and r))
return not x or y
tt(prob13,3)
#Question#2----------------------------------------
#(p=>q)=>r=p=>(q=>r)
def prob14(p,q,r):
x=(not(not p or q) or r)
y=(not p or (not q or r))
return x==y
tt(prob14,3)
def prob15(p, q):
x = not(p and q)
y = not p and not q
return x == y
tt(prob15, 2)
def prob16(p, q):
x = not(p or q)
y = not p or not q
return x == y
tt(prob16, 2)
def prob17(p):
x = p
y = not p
return x == y
tt(prob17, 1)

Sort a List of Strings

0 likes • Oct 15, 2022 • 2 views
Python
my_list = ["blue", "red", "green"]
#1- Using sort or srted directly or with specifc keys
my_list.sort() #sorts alphabetically or in an ascending order for numeric data
my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest.
# You can use reverse=True to flip the order
#2- Using locale and functools
import locale
from functools import cmp_to_key
my_list = sorted(my_list, key=cmp_to_key(locale.strcoll))

ZapFinder

0 likes • Jan 23, 2021 • 0 views
Python
import subprocess #for the praat calls
import os #for ffmpeg and the pause call at the end
#Even if we wanted all videos being rendered asynchronously, we couldn't see progress or errors
import glob #for the ambiguous files
import tempfile
audioFileDirectory = 'Audio Files'
timeList = {}
fileList = glob.glob(audioFileDirectory + '\\*.wav')
pipeList = {}
for fileName in fileList:
arglist = ['Praat.exe', '--run', 'crosscorrelateMatch.praat', 'zeussound.wav', fileName, "0" , "300"]
print(' '.join(arglist))
pipe = subprocess.Popen(arglist, stdout=subprocess.PIPE)
pipeList[fileName[len(audioFileDirectory)+1:-4]] = pipe #+1 because of back slash, -4 because .wav
#for fileName, pipe in pipeList.items():
# text = pipe.communicate()[0].decode('utf-8')
# timeList[fileName] = float(text[::2])
for fileName, pipe in pipeList.items():
if float(pipe.communicate()[0].decode('utf-8')[::2]) > .0003: #.000166 is not a match, and .00073 is a perfect match. .00053 is a tested match
arglist = ['Praat.exe', '--run', 'crosscorrelate.praat', 'zeussound.wav', audioFileDirectory + '\\' + fileName + '.wav', "0" , "300"]
print(' '.join(arglist))
text = subprocess.Popen(arglist, stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
timeList[fileName] = float(text[::2])
clipLength = 10
for fileName, time in timeList.items():
arglist = ['ffmpeg', '-i', '"'+fileName+'.mp4"', '-ss', str(time-clipLength), '-t', str(clipLength*2), '-acodec', 'copy' , '-vcodec', 'copy', '"ZEUS'+ fileName + '.mp4"']
print(' '.join(arglist))
os.system(' '.join(arglist))
tempFile = tempfile.NamedTemporaryFile(delete=False)
for fileName in glob.glob('ZEUS*.mp4'):
tempFile.write(("file '" + os.path.realpath(fileName) + "'\n").encode());
tempFile.seek(0)
print(tempFile.read())
tempFile.close()
arglist = ['ffmpeg', '-safe', '0', '-f', 'concat', '-i', '"'+tempFile.name+'"', '-c', 'copy', 'ZeusMontage.mp4']
print(' '.join(arglist))
os.system(' '.join(arglist))
os.unlink(tempFile.name) #Delete the temp file
#print(timeList)
os.system('PAUSE')

Number guessing game

0 likes • Nov 19, 2022 • 0 views
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()