Resolving conflict

This commit is contained in:
Akshath 2023-10-24 18:34:49 +05:30
parent 790529ee12
commit a0d4e04a3c
56 changed files with 95733 additions and 95733 deletions

View File

@ -1,256 +1,256 @@
import tkinter as tk import tkinter as tk
import random import random
import colors as c import colors as c
class Game(tk.Frame): class Game(tk.Frame):
def __init__(self): def __init__(self):
tk.Frame.__init__(self) tk.Frame.__init__(self)
self.grid() self.grid()
self.master.title('2048') self.master.title('2048')
self.main_grid = tk.Frame( self.main_grid = tk.Frame(
self, bg=c.GRID_COLOR, bd=3, width=400, height=400) self, bg=c.GRID_COLOR, bd=3, width=400, height=400)
self.main_grid.grid(pady=(100, 0)) self.main_grid.grid(pady=(100, 0))
self.make_GUI() self.make_GUI()
self.start_game() self.start_game()
self.master.bind("<Left>", self.left) self.master.bind("<Left>", self.left)
self.master.bind("<Right>", self.right) self.master.bind("<Right>", self.right)
self.master.bind("<Up>", self.up) self.master.bind("<Up>", self.up)
self.master.bind("<Down>", self.down) self.master.bind("<Down>", self.down)
self.mainloop() self.mainloop()
def make_GUI(self): def make_GUI(self):
# make grid # make grid
self.cells = [] self.cells = []
for i in range(4): for i in range(4):
row = [] row = []
for j in range(4): for j in range(4):
cell_frame = tk.Frame( cell_frame = tk.Frame(
self.main_grid, self.main_grid,
bg=c.EMPTY_CELL_COLOR, bg=c.EMPTY_CELL_COLOR,
width=100, width=100,
height=100) height=100)
cell_frame.grid(row=i, column=j, padx=5, pady=5) cell_frame.grid(row=i, column=j, padx=5, pady=5)
cell_number = tk.Label(self.main_grid, bg=c.EMPTY_CELL_COLOR) cell_number = tk.Label(self.main_grid, bg=c.EMPTY_CELL_COLOR)
cell_number.grid(row=i, column=j) cell_number.grid(row=i, column=j)
cell_data = {"frame": cell_frame, "number": cell_number} cell_data = {"frame": cell_frame, "number": cell_number}
row.append(cell_data) row.append(cell_data)
self.cells.append(row) self.cells.append(row)
# make score header # make score header
score_frame = tk.Frame(self) score_frame = tk.Frame(self)
score_frame.place(relx=0.5, y=40, anchor="center") score_frame.place(relx=0.5, y=40, anchor="center")
tk.Label( tk.Label(
score_frame, score_frame,
text="Score", text="Score",
font=c.SCORE_LABEL_FONT).grid(row=0) font=c.SCORE_LABEL_FONT).grid(row=0)
self.score_label = tk.Label(score_frame, text="0", font=c.SCORE_FONT) self.score_label = tk.Label(score_frame, text="0", font=c.SCORE_FONT)
self.score_label.grid(row=1) self.score_label.grid(row=1)
def start_game(self): def start_game(self):
# create matrix of zeroes # create matrix of zeroes
self.matrix = [[0] * 4 for _ in range(4)] self.matrix = [[0] * 4 for _ in range(4)]
# fill 2 random cells with 2s # fill 2 random cells with 2s
row = random.randint(0, 3) row = random.randint(0, 3)
col = random.randint(0, 3) col = random.randint(0, 3)
self.matrix[row][col] = 2 self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2]) self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure( self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2], bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2], fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2], font=c.CELL_NUMBER_FONTS[2],
text="2" text="2"
) )
while(self.matrix[row][col] != 0): while(self.matrix[row][col] != 0):
row = random.randint(0, 3) row = random.randint(0, 3)
col = random.randint(0, 3) col = random.randint(0, 3)
self.matrix[row][col] = 2 self.matrix[row][col] = 2
self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2]) self.cells[row][col]["frame"].configure(bg=c.CELL_COLORS[2])
self.cells[row][col]["number"].configure( self.cells[row][col]["number"].configure(
bg=c.CELL_COLORS[2], bg=c.CELL_COLORS[2],
fg=c.CELL_NUMBER_COLORS[2], fg=c.CELL_NUMBER_COLORS[2],
font=c.CELL_NUMBER_FONTS[2], font=c.CELL_NUMBER_FONTS[2],
text="2" text="2"
) )
self.score = 0 self.score = 0
# Matrix Manipulation Functions # Matrix Manipulation Functions
def stack(self): def stack(self):
new_matrix = [[0] * 4 for _ in range(4)] new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4): for i in range(4):
fill_position = 0 fill_position = 0
for j in range(4): for j in range(4):
if self.matrix[i][j] != 0: if self.matrix[i][j] != 0:
new_matrix[i][fill_position] = self.matrix[i][j] new_matrix[i][fill_position] = self.matrix[i][j]
fill_position += 1 fill_position += 1
self.matrix = new_matrix self.matrix = new_matrix
def combine(self): def combine(self):
for i in range(4): for i in range(4):
for j in range(3): for j in range(3):
if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]: if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]:
self.matrix[i][j] *= 2 self.matrix[i][j] *= 2
self.matrix[i][j + 1] = 0 self.matrix[i][j + 1] = 0
self.score += self.matrix[i][j] self.score += self.matrix[i][j]
def reverse(self): def reverse(self):
new_matrix = [] new_matrix = []
for i in range(4): for i in range(4):
new_matrix.append([]) new_matrix.append([])
for j in range(4): for j in range(4):
new_matrix[i].append(self.matrix[i][3 - j]) new_matrix[i].append(self.matrix[i][3 - j])
self.matrix = new_matrix self.matrix = new_matrix
def transpose(self): def transpose(self):
new_matrix = [[0] * 4 for _ in range(4)] new_matrix = [[0] * 4 for _ in range(4)]
for i in range(4): for i in range(4):
for j in range(4): for j in range(4):
new_matrix[i][j] = self.matrix[j][i] new_matrix[i][j] = self.matrix[j][i]
self.matrix = new_matrix self.matrix = new_matrix
# Add a new 2 or 4 tile randomly to an empty cell # Add a new 2 or 4 tile randomly to an empty cell
def add_new_tile(self): def add_new_tile(self):
row = random.randint(0, 3) row = random.randint(0, 3)
col = random.randint(0, 3) col = random.randint(0, 3)
while(self.matrix[row][col] != 0): while(self.matrix[row][col] != 0):
row = random.randint(0, 3) row = random.randint(0, 3)
col = random.randint(0, 3) col = random.randint(0, 3)
self.matrix[row][col] = random.choice([2, 4]) # create new tile of 2 or 4 at any random row & col self.matrix[row][col] = random.choice([2, 4]) # create new tile of 2 or 4 at any random row & col
# Update the GUI to match the matrix # Update the GUI to match the matrix
def update_GUI(self): def update_GUI(self):
for i in range(4): for i in range(4):
for j in range(4): for j in range(4):
cell_value = self.matrix[i][j] cell_value = self.matrix[i][j]
if cell_value == 0: if cell_value == 0:
self.cells[i][j]["frame"].configure(bg=c.EMPTY_CELL_COLOR) # give bgcolor to empty cell's frame self.cells[i][j]["frame"].configure(bg=c.EMPTY_CELL_COLOR) # give bgcolor to empty cell's frame
self.cells[i][j]["number"].configure( # give bgcolor to empty cell's number self.cells[i][j]["number"].configure( # give bgcolor to empty cell's number
bg=c.EMPTY_CELL_COLOR, text="") bg=c.EMPTY_CELL_COLOR, text="")
else: else:
self.cells[i][j]["frame"].configure( # give cell colour's value to filled cell's frame self.cells[i][j]["frame"].configure( # give cell colour's value to filled cell's frame
bg=c.CELL_COLORS[cell_value]) bg=c.CELL_COLORS[cell_value])
self.cells[i][j]["number"].configure( self.cells[i][j]["number"].configure(
bg=c.CELL_COLORS[cell_value], bg=c.CELL_COLORS[cell_value],
fg=c.CELL_NUMBER_COLORS[cell_value], fg=c.CELL_NUMBER_COLORS[cell_value],
font=c.CELL_NUMBER_FONTS[cell_value], font=c.CELL_NUMBER_FONTS[cell_value],
text=str(cell_value)) text=str(cell_value))
self.score_label.configure(text=self.score) self.score_label.configure(text=self.score)
self.update_idletasks() self.update_idletasks()
# Arrow-Press Functions # Arrow-Press Functions
def left(self, event): def left(self, event):
self.stack() self.stack()
self.combine() self.combine()
self.stack() self.stack()
self.add_new_tile() self.add_new_tile()
self.update_GUI() self.update_GUI()
self.game_over() self.game_over()
def right(self, event): def right(self, event):
self.reverse() self.reverse()
self.stack() self.stack()
self.combine() self.combine()
self.stack() self.stack()
self.reverse() self.reverse()
self.add_new_tile() self.add_new_tile()
self.update_GUI() self.update_GUI()
self.game_over() self.game_over()
def up(self, event): def up(self, event):
self.transpose() self.transpose()
self.stack() self.stack()
self.combine() self.combine()
self.stack() self.stack()
self.transpose() self.transpose()
self.add_new_tile() self.add_new_tile()
self.update_GUI() self.update_GUI()
self.game_over() self.game_over()
def down(self, event): def down(self, event):
self.transpose() self.transpose()
self.reverse() self.reverse()
self.stack() self.stack()
self.combine() self.combine()
self.stack() self.stack()
self.reverse() self.reverse()
self.transpose() self.transpose()
self.add_new_tile() self.add_new_tile()
self.update_GUI() self.update_GUI()
self.game_over() self.game_over()
# Check if any moves are possible # Check if any moves are possible
def horizontal_move_exists(self): def horizontal_move_exists(self):
for i in range(4): for i in range(4):
for j in range(3): for j in range(3):
if self.matrix[i][j] == self.matrix[i][j + 1]: if self.matrix[i][j] == self.matrix[i][j + 1]:
return True return True
return False return False
def vertical_move_exists(self): def vertical_move_exists(self):
for i in range(3): for i in range(3):
for j in range(4): for j in range(4):
if self.matrix[i][j] == self.matrix[i + 1][j]: if self.matrix[i][j] == self.matrix[i + 1][j]:
return True return True
return False return False
# Check if Game is Over (Win/Lose) # Check if Game is Over (Win/Lose)
def game_over(self): def game_over(self):
if any(2048 in row for row in self.matrix): if any(2048 in row for row in self.matrix):
game_over_frame = tk.Frame(self.main_grid, borderwidth=2) game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center") game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label( tk.Label(
game_over_frame, game_over_frame,
text="You win!", text="You win!",
bg=c.WINNER_BG, bg=c.WINNER_BG,
fg=c.GAME_OVER_FONT_COLOR, fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack() font=c.GAME_OVER_FONT).pack()
elif not any(0 in row for row in self.matrix) and not self.horizontal_move_exists()\ elif not any(0 in row for row in self.matrix) and not self.horizontal_move_exists()\
and not self.vertical_move_exists(): and not self.vertical_move_exists():
game_over_frame = tk.Frame(self.main_grid, borderwidth=2) game_over_frame = tk.Frame(self.main_grid, borderwidth=2)
game_over_frame.place(relx=0.5, rely=0.5, anchor="center") game_over_frame.place(relx=0.5, rely=0.5, anchor="center")
tk.Label( tk.Label(
game_over_frame, game_over_frame,
text="Game over!", text="Game over!",
bg=c.LOSER_BG, bg=c.LOSER_BG,
fg=c.GAME_OVER_FONT_COLOR, fg=c.GAME_OVER_FONT_COLOR,
font=c.GAME_OVER_FONT).pack() font=c.GAME_OVER_FONT).pack()
def main(): def main():
Game() Game()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -1,50 +1,50 @@
GRID_COLOR = "#a39489" GRID_COLOR = "#a39489"
EMPTY_CELL_COLOR = "#c2b3a9" EMPTY_CELL_COLOR = "#c2b3a9"
SCORE_LABEL_FONT = ("Verdana", 20) SCORE_LABEL_FONT = ("Verdana", 20)
SCORE_FONT = ("Helvetica", 32, "bold") SCORE_FONT = ("Helvetica", 32, "bold")
GAME_OVER_FONT = ("Helvetica", 48, "bold") GAME_OVER_FONT = ("Helvetica", 48, "bold")
GAME_OVER_FONT_COLOR = "#ffffff" GAME_OVER_FONT_COLOR = "#ffffff"
WINNER_BG = "#ffcc00" WINNER_BG = "#ffcc00"
LOSER_BG = "#a39489" LOSER_BG = "#a39489"
CELL_COLORS = { CELL_COLORS = {
2: "#fcefe6", 2: "#fcefe6",
4: "#f2e8cb", 4: "#f2e8cb",
8: "#f5b682", 8: "#f5b682",
16: "#f29446", 16: "#f29446",
32: "#ff775c", 32: "#ff775c",
64: "#e64c2e", 64: "#e64c2e",
128: "#ede291", 128: "#ede291",
256: "#fce130", 256: "#fce130",
512: "#ffdb4a", 512: "#ffdb4a",
1024: "#f0b922", 1024: "#f0b922",
2048: "#fad74d" 2048: "#fad74d"
} }
CELL_NUMBER_COLORS = { CELL_NUMBER_COLORS = {
2: "#695c57", 2: "#695c57",
4: "#695c57", 4: "#695c57",
8: "#ffffff", 8: "#ffffff",
16: "#ffffff", 16: "#ffffff",
32: "#ffffff", 32: "#ffffff",
64: "#ffffff", 64: "#ffffff",
128: "#ffffff", 128: "#ffffff",
256: "#ffffff", 256: "#ffffff",
512: "#ffffff", 512: "#ffffff",
1024: "#ffffff", 1024: "#ffffff",
2048: "#ffffff" 2048: "#ffffff"
} }
CELL_NUMBER_FONTS = { CELL_NUMBER_FONTS = {
2: ("Helvetica", 55, "bold"), 2: ("Helvetica", 55, "bold"),
4: ("Helvetica", 55, "bold"), 4: ("Helvetica", 55, "bold"),
8: ("Helvetica", 55, "bold"), 8: ("Helvetica", 55, "bold"),
16: ("Helvetica", 50, "bold"), 16: ("Helvetica", 50, "bold"),
32: ("Helvetica", 50, "bold"), 32: ("Helvetica", 50, "bold"),
64: ("Helvetica", 50, "bold"), 64: ("Helvetica", 50, "bold"),
128: ("Helvetica", 45, "bold"), 128: ("Helvetica", 45, "bold"),
256: ("Helvetica", 45, "bold"), 256: ("Helvetica", 45, "bold"),
512: ("Helvetica", 45, "bold"), 512: ("Helvetica", 45, "bold"),
1024: ("Helvetica", 40, "bold"), 1024: ("Helvetica", 40, "bold"),
2048: ("Helvetica", 40, "bold") 2048: ("Helvetica", 40, "bold")
} }

View File

@ -1,127 +1,127 @@
import random import random
print("wassup hommie, care to play a game?") print("wassup hommie, care to play a game?")
print("i'll try to guess the number YOU choose.") print("i'll try to guess the number YOU choose.")
print("please tell me the borders: ") print("please tell me the borders: ")
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
while True: while True:
if(a > b): if(a > b):
(print("error, min can't be more than max. ")) (print("error, min can't be more than max. "))
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
else: else:
break; break;
breaking = "------------" breaking = "------------"
print("now type in the number: ") print("now type in the number: ")
c = int(input(" ")) c = int(input(" "))
tries = 1; tries = 1;
d = random.randint(a, b) d = random.randint(a, b)
while True: while True:
if(d == c and tries == 1): if(d == c and tries == 1):
print("guess 1: " + str(d)) print("guess 1: " + str(d))
print("HA, gotcha. I got it in 1 time!") print("HA, gotcha. I got it in 1 time!")
print("Wanna go again? y for yes and anykey for no. ") print("Wanna go again? y for yes and anykey for no. ")
i = input(""); i = input("");
if(i == "y"): if(i == "y"):
print(breaking * 10); print(breaking * 10);
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
tries = 1; tries = 1;
if(a > b): if(a > b):
print("error, min can't be more than max. ") print("error, min can't be more than max. ")
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
else: else:
d = random.randint(a, b) d = random.randint(a, b)
else: else:
break; break;
elif(d == c): elif(d == c):
print("HA, gotcha. I got it in " + str(tries - 1) + " times!") print("HA, gotcha. I got it in " + str(tries - 1) + " times!")
print("Wanna go again? y for yes and anykey for no. ") print("Wanna go again? y for yes and anykey for no. ")
i = input(""); i = input("");
if(i == "y"): if(i == "y"):
print(breaking * 10); print(breaking * 10);
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
tries = 1; tries = 1;
if(a > b): if(a > b):
print("error, min can't be more than max. ") print("error, min can't be more than max. ")
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
else: else:
d = random.randint(a, b) d = random.randint(a, b)
else: else:
break; break;
elif(c > b): elif(c > b):
print("error, number can't be bigger than max."); print("error, number can't be bigger than max.");
print("Wanna go again? y for yes and anykey for no. ") print("Wanna go again? y for yes and anykey for no. ")
i = input(""); i = input("");
if(i == "y"): if(i == "y"):
print(breaking * 10); print(breaking * 10);
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
tries = 1; tries = 1;
if(a > b): if(a > b):
(print("error, min can't be more than max. ")) (print("error, min can't be more than max. "))
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
else: else:
d = random.randint(a, b) d = random.randint(a, b)
else: else:
break; break;
elif(c < a): elif(c < a):
print("error, number can't be smaller than min."); print("error, number can't be smaller than min.");
print("Wanna go again? y for yes and anykey for no. ") print("Wanna go again? y for yes and anykey for no. ")
i = input(""); i = input("");
if(i == "y"): if(i == "y"):
print(breaking * 10); print(breaking * 10);
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
tries = 1; tries = 1;
if(a > b): if(a > b):
print("error, min can't be more than max. ") print("error, min can't be more than max. ")
a = int(input("Min: ")) a = int(input("Min: "))
b = int(input("Max: ")) b = int(input("Max: "))
print("now type in the number") print("now type in the number")
c = int(input(" ")) c = int(input(" "))
else: else:
d = random.randint(a, b) d = random.randint(a, b)
else: else:
break; break;
elif(d < c): elif(d < c):
a = d + 1; a = d + 1;
d = random.randint(a, b) d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d)); print( "guess " + str(tries) + " :" + str(d));
tries += 1; tries += 1;
elif(d > c): elif(d > c):
b = d - 1; b = d - 1;
d = random.randint(a, b) d = random.randint(a, b)
print( "guess " + str(tries) + " :" + str(d)) print( "guess " + str(tries) + " :" + str(d))
tries += 1 tries += 1
input="" input=""

View File

@ -1,7 +1,7 @@
id,file_name,file_url,download_date,download_status id,file_name,file_url,download_date,download_status
1430,sample_video1.mp4,https://example.com/download/sample_video1.mp4,05/10/22, 1430,sample_video1.mp4,https://example.com/download/sample_video1.mp4,05/10/22,
239,sample_video2.mp4,https://example.com/download/sample_video2.mp4,05/10/22, 239,sample_video2.mp4,https://example.com/download/sample_video2.mp4,05/10/22,
3421,sample_video3.mp4,https://example.com/download/sample_video3.mp4,05/10/22, 3421,sample_video3.mp4,https://example.com/download/sample_video3.mp4,05/10/22,
1305,sample_video4.mp4,https://example.com/download/sample_video4.mp4,05/10/22, 1305,sample_video4.mp4,https://example.com/download/sample_video4.mp4,05/10/22,
6375,sample_video5.mp4,https://example.com/download/sample_video5.mp4,06/10/22,done 6375,sample_video5.mp4,https://example.com/download/sample_video5.mp4,06/10/22,done
1203,sample_video6.mp4,https://example.com/download/sample_video6.mp4,06/10/22,done 1203,sample_video6.mp4,https://example.com/download/sample_video6.mp4,06/10/22,done

1 id file_name file_url download_date download_status
2 1430 sample_video1.mp4 https://example.com/download/sample_video1.mp4 05/10/22
3 239 sample_video2.mp4 https://example.com/download/sample_video2.mp4 05/10/22
4 3421 sample_video3.mp4 https://example.com/download/sample_video3.mp4 05/10/22
5 1305 sample_video4.mp4 https://example.com/download/sample_video4.mp4 05/10/22
6 6375 sample_video5.mp4 https://example.com/download/sample_video5.mp4 06/10/22 done
7 1203 sample_video6.mp4 https://example.com/download/sample_video6.mp4 06/10/22 done

View File

@ -1,92 +1,92 @@
#!/usr/bin/python #!/usr/bin/python
import sys import sys
import copy import copy
import argparse import argparse
import itertools import itertools
def parse_arguments(): def parse_arguments():
parser = argparse.ArgumentParser(description = 'Countdown - Numbers Game', parser = argparse.ArgumentParser(description = 'Countdown - Numbers Game',
add_help = False) add_help = False)
parser._optionals.title = 'Target and List Numbers' parser._optionals.title = 'Target and List Numbers'
parser.add_argument('-h', '--help', action = 'help', parser.add_argument('-h', '--help', action = 'help',
default = argparse.SUPPRESS, default = argparse.SUPPRESS,
help = 'Countdown Numbers Game. Inform a list of six numbers (-l) and a target (-t).') help = 'Countdown Numbers Game. Inform a list of six numbers (-l) and a target (-t).')
parser.add_argument('-t', '--target', type = int, action = 'store', parser.add_argument('-t', '--target', type = int, action = 'store',
dest = 'target', default = 100, help = 'The target of the game.') dest = 'target', default = 100, help = 'The target of the game.')
parser.add_argument('-l', '--list', type = int, nargs = '+', parser.add_argument('-l', '--list', type = int, nargs = '+',
default = [1, 2, 4, 8, 10, 25], help = 'List with six integers.') default = [1, 2, 4, 8, 10, 25], help = 'List with six integers.')
arguments = parser.parse_args() arguments = parser.parse_args()
return arguments return arguments
pd = {} pd = {}
def nubmers_game(L, t, s, ol): def nubmers_game(L, t, s, ol):
global pd global pd
ops = ['+', '-', '*', '/'] ops = ['+', '-', '*', '/']
ss = copy.deepcopy(s) ss = copy.deepcopy(s)
key = str((ss, L)) key = str((ss, L))
if key in pd: if key in pd:
return pd[key] return pd[key]
if len(L) == 1: if len(L) == 1:
if L[0] == t: if L[0] == t:
print(f'Target: {t}\nNumbers: {ol}\nSolution: {ss}') print(f'Target: {t}\nNumbers: {ol}\nSolution: {ss}')
return True return True
else: else:
pd[key] = False pd[key] = False
return False return False
else: else:
for c in itertools.combinations(L, 2): for c in itertools.combinations(L, 2):
if not c[0] or not c[1]: if not c[0] or not c[1]:
continue continue
tmp = L[:] tmp = L[:]
tmp.remove(c[0]) tmp.remove(c[0])
tmp.remove(c[1]) tmp.remove(c[1])
exp1 = f'{c[0]} %s {c[1]}' exp1 = f'{c[0]} %s {c[1]}'
exp2 = f'{c[1]} %s {c[0]}' exp2 = f'{c[1]} %s {c[0]}'
if nubmers_game(tmp + [c[0] + c[1]], t, ss + [exp1 % ('+')], ol): if nubmers_game(tmp + [c[0] + c[1]], t, ss + [exp1 % ('+')], ol):
return True return True
elif nubmers_game(tmp + [c[0] - c[1]], t, ss + [exp1 % ('-')], ol): elif nubmers_game(tmp + [c[0] - c[1]], t, ss + [exp1 % ('-')], ol):
return True return True
elif nubmers_game(tmp + [c[1] - c[0]], t, ss + [exp2 % ('-')], ol): elif nubmers_game(tmp + [c[1] - c[0]], t, ss + [exp2 % ('-')], ol):
return True return True
elif nubmers_game(tmp + [c[0] * c[1]], t, ss + [exp1 % ('*')], ol): elif nubmers_game(tmp + [c[0] * c[1]], t, ss + [exp1 % ('*')], ol):
return True return True
elif c[0] % c[1] == 0 and nubmers_game(tmp + [c[0] // c[1]], t, ss + [exp1 % ('/')], ol): elif c[0] % c[1] == 0 and nubmers_game(tmp + [c[0] // c[1]], t, ss + [exp1 % ('/')], ol):
return True return True
elif c[1] % c[0] == 0 and nubmers_game(tmp + [c[1] // c[0]], t, ss + [exp2 % ('/')], ol): elif c[1] % c[0] == 0 and nubmers_game(tmp + [c[1] // c[0]], t, ss + [exp2 % ('/')], ol):
return True return True
elif nubmers_game(tmp + [c[0]], t, ss, ol): elif nubmers_game(tmp + [c[0]], t, ss, ol):
return True return True
elif nubmers_game(tmp + [c[1]], t, ss, ol): elif nubmers_game(tmp + [c[1]], t, ss, ol):
return True return True
pd[key] = False pd[key] = False
return False return False
if __name__ == '__main__': if __name__ == '__main__':
args = parse_arguments() args = parse_arguments()
if len(args.list) != 6: if len(args.list) != 6:
print(f'The set of numbers in Countdown is 6.') print(f'The set of numbers in Countdown is 6.')
sys.exit(-1) sys.exit(-1)
if args.target < 0 or args.target > 999: if args.target < 0 or args.target > 999:
print(f'The target number in Countdown is between 0 and 999.') print(f'The target number in Countdown is between 0 and 999.')
sys.exit(-1) sys.exit(-1)
if not nubmers_game(args.list, args.target, [], args.list): if not nubmers_game(args.list, args.target, [], args.list):
print(f'Target: {args.target}') print(f'Target: {args.target}')
print(f'Numbers: {args.list}') print(f'Numbers: {args.list}')
print(f'Solution: Not found.') print(f'Solution: Not found.')

0
Crypt_Socket/cryptSocket_cliente.py Executable file → Normal file
View File

0
Crypt_Socket/cryptSocket_servidor.py Executable file → Normal file
View File

0
DOH-Dig/doh-dig Executable file → Normal file
View File

View File

@ -1,24 +1,24 @@
import os import os
import shutil import shutil
#The Path of the directory to be sorted #The Path of the directory to be sorted
path = 'C:\\Users\\<USERNAME>\\Downloads' path = 'C:\\Users\\<USERNAME>\\Downloads'
#This populates a list with the filenames in the directory #This populates a list with the filenames in the directory
list_ = os.listdir(path) list_ = os.listdir(path)
#Traverses every file #Traverses every file
for file_ in list_: for file_ in list_:
name,ext = os.path.splitext(file_) name,ext = os.path.splitext(file_)
print(name) print(name)
#Stores the extension type #Stores the extension type
ext = ext[1:] ext = ext[1:]
#If it is directory, it forces the next iteration #If it is directory, it forces the next iteration
if ext == '': if ext == '':
continue continue
#If a directory with the name 'ext' exists, it moves the file to that directory #If a directory with the name 'ext' exists, it moves the file to that directory
if os.path.exists(path+'/'+ext): if os.path.exists(path+'/'+ext):
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_) shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)
#If the directory does not exist, it creates a new directory #If the directory does not exist, it creates a new directory
else: else:
os.makedirs(path+'/'+ext) os.makedirs(path+'/'+ext)
shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_) shutil.move(path+'/'+file_,path+'/'+ext+'/'+file_)

View File

@ -1,207 +1,207 @@
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging import logging
import os import os
import telegram import telegram
import shutil import shutil
# Enable logging # Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO) level=logging.INFO)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
#list of authorized users #list of authorized users
#create a list of telegram usernames to authorise them, 0th username is admin. #create a list of telegram usernames to authorise them, 0th username is admin.
username_list = [] username_list = []
# Define a few command handlers. These usually take the two arguments bot and # Define a few command handlers. These usually take the two arguments bot and
# update. Error handlers also receive the raised TelegramError object in error. # update. Error handlers also receive the raised TelegramError object in error.
def start(bot, update): def start(bot, update):
"""Send a message when the command /start is issued.""" """Send a message when the command /start is issued."""
reply = "Welcome to World of Automation. \nI am a bot developed by a Lazy Programmer.\nSend /help command to see what i can do." reply = "Welcome to World of Automation. \nI am a bot developed by a Lazy Programmer.\nSend /help command to see what i can do."
update.message.reply_text(reply) update.message.reply_text(reply)
def help(bot, update): def help(bot, update):
"""Send a message when the command /help is issued.""" """Send a message when the command /help is issued."""
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
reply = '''Send /get folder_name/file_name.extension to receive a file. reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files. \nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file. \nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder. \nSend /mkdir folder_name to create a Folder.
\nSend /remove folder_name/filename.extension to delete a file. \nSend /remove folder_name/filename.extension to delete a file.
\nSend /adduser username to give access. \nSend /adduser username to give access.
\nSend /removeuser username to revoke access. \nSend /removeuser username to revoke access.
\nSend /showuser to show list of users \nSend /showuser to show list of users
''' '''
else: else:
reply = '''Send /get folder_name/file_name.extension to receive a file. reply = '''Send /get folder_name/file_name.extension to receive a file.
\nSend /ls folder_name to show list of files. \nSend /ls folder_name to show list of files.
\nSend /put folder_name/file_name.extension to upload last sent file. \nSend /put folder_name/file_name.extension to upload last sent file.
\nSend /mkdir folder_name to create a Folder. \nSend /mkdir folder_name to create a Folder.
''' '''
update.message.reply_text(reply) update.message.reply_text(reply)
def get(bot, update): def get(bot, update):
"""Send requested file.""" """Send requested file."""
username = update.message.from_user.username username = update.message.from_user.username
if(username not in username_list): if(username not in username_list):
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
return return
file = update.message.text.split(" ")[-1] file = update.message.text.split(" ")[-1]
if(file == "/send"): if(file == "/send"):
update.message.reply_text("Invalid File name.") update.message.reply_text("Invalid File name.")
else: else:
reply = "Findind and Sending a requested file to you. Hold on..." reply = "Findind and Sending a requested file to you. Hold on..."
update.message.reply_text(reply) update.message.reply_text(reply)
path = os.getcwd()+'/'+file path = os.getcwd()+'/'+file
if (os.path.exists(path)): if (os.path.exists(path)):
bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100) bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100)
else: else:
update.message.reply_text("File not Found.") update.message.reply_text("File not Found.")
def ls(bot, update): def ls(bot, update):
"""Show files in requested directory.""" """Show files in requested directory."""
username = update.message.from_user.username username = update.message.from_user.username
if(username not in username_list): if(username not in username_list):
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
return return
file = update.message.text.split(" ")[-1] file = update.message.text.split(" ")[-1]
if(file == "/show"): if(file == "/show"):
update.message.reply_text("Invalid Directory name.") update.message.reply_text("Invalid Directory name.")
else: else:
reply = "Findind and Sending a list of files to you. Hold on..." reply = "Findind and Sending a list of files to you. Hold on..."
update.message.reply_text(reply) update.message.reply_text(reply)
path = os.getcwd()+'/'+file path = os.getcwd()+'/'+file
if (os.path.exists(path)): if (os.path.exists(path)):
update.message.reply_text(os.listdir(path)) update.message.reply_text(os.listdir(path))
else: else:
update.message.reply_text("Directory not Found.") update.message.reply_text("Directory not Found.")
def put(bot, update): def put(bot, update):
f = open(str(os.getcwd())+"/file", "r") f = open(str(os.getcwd())+"/file", "r")
file_id = f.read() file_id = f.read()
f.close f.close
if file_id == "": if file_id == "":
update.message.reply_text("You didn't upload file.") update.message.reply_text("You didn't upload file.")
else: else:
new_file = bot.get_file(file_id) new_file = bot.get_file(file_id)
message = update.message.text.split(" ") message = update.message.text.split(" ")
path = message[-1] path = message[-1]
if len(path) < 1: if len(path) < 1:
update.message.reply_text("Enter Path correctly.") update.message.reply_text("Enter Path correctly.")
else: else:
new_file.download(os.getcwd()+'/'+path) new_file.download(os.getcwd()+'/'+path)
update.message.reply_text("File Stored.") update.message.reply_text("File Stored.")
def mkdir(bot, update): def mkdir(bot, update):
message = update.message.text.split(" ") message = update.message.text.split(" ")
if len(message) < 1 or message[-1] == "/mkdir": if len(message) < 1 or message[-1] == "/mkdir":
update.message.reply_text("Invalid Syntax. Refer syntax in help section.") update.message.reply_text("Invalid Syntax. Refer syntax in help section.")
return return
path = os.getcwd() + "/" + message[-1] path = os.getcwd() + "/" + message[-1]
os.mkdir(path) os.mkdir(path)
update.message.reply_text("Folder Created.") update.message.reply_text("Folder Created.")
def echo(bot, update): def echo(bot, update):
"""Echo the user message.""" """Echo the user message."""
if update.message.document: if update.message.document:
file_id = update.message.document.file_id file_id = update.message.document.file_id
f = open(str(os.getcwd())+"/file", "w") f = open(str(os.getcwd())+"/file", "w")
f.write(file_id) f.write(file_id)
f.close f.close
update.message.reply_text("Received.Now send file name and location to store. using /put command") update.message.reply_text("Received.Now send file name and location to store. using /put command")
else: else:
reply = "Invalid Input." reply = "Invalid Input."
update.message.reply_text(reply) update.message.reply_text(reply)
def error(bot, update, error): def error(bot, update, error):
"""Log Errors caused by Updates.""" """Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error) logger.warning('Update "%s" caused error "%s"', update, error)
def add_user(bot, update): def add_user(bot, update):
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
username = update.message.text.split(" ")[-1] username = update.message.text.split(" ")[-1]
username_list.append(username) username_list.append(username)
update.message.reply_text("User added.") update.message.reply_text("User added.")
else: else:
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
def show_user(bot, update): def show_user(bot, update):
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
update.message.reply_text(username_list) update.message.reply_text(username_list)
else: else:
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
def remove_user(bot, update): def remove_user(bot, update):
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
username = update.message.text.split(" ")[-1] username = update.message.text.split(" ")[-1]
username_list.remove(username) username_list.remove(username)
update.message.reply_text("User Removed.") update.message.reply_text("User Removed.")
else: else:
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
def remove(bot, update): def remove(bot, update):
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
filename = update.message.text.split(" ")[-1] filename = update.message.text.split(" ")[-1]
os.remove(os.getcwd()+ "/" + filename) os.remove(os.getcwd()+ "/" + filename)
update.message.reply_text("File Removed.") update.message.reply_text("File Removed.")
else: else:
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
def rmdir(bot, update): def rmdir(bot, update):
admin = update.message.from_user.username admin = update.message.from_user.username
if admin == username_list[0]: if admin == username_list[0]:
filename = update.message.text.split(" ")[-1] filename = update.message.text.split(" ")[-1]
shutil.rmtree(os.getcwd()+ "/" + filename) shutil.rmtree(os.getcwd()+ "/" + filename)
update.message.reply_text("Folder Removed.") update.message.reply_text("Folder Removed.")
else: else:
update.message.reply_text("You are not Authorized.") update.message.reply_text("You are not Authorized.")
def main(): def main():
"""Start the bot.""" """Start the bot."""
# Create the EventHandler and pass it your bot's token. # Create the EventHandler and pass it your bot's token.
TOKEN = os.environ['TOKEN'] TOKEN = os.environ['TOKEN']
updater = Updater(TOKEN) updater = Updater(TOKEN)
# Get the dispatcher to register handlers # Get the dispatcher to register handlers
dp = updater.dispatcher dp = updater.dispatcher
# on different commands - answer in Telegram # on different commands - answer in Telegram
dp.add_handler(CommandHandler("start", start)) dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help)) dp.add_handler(CommandHandler("help", help))
dp.add_handler(CommandHandler("get", get)) dp.add_handler(CommandHandler("get", get))
dp.add_handler(CommandHandler("ls", ls)) dp.add_handler(CommandHandler("ls", ls))
dp.add_handler(CommandHandler("put", put)) dp.add_handler(CommandHandler("put", put))
dp.add_handler(CommandHandler("mkdir", mkdir)) dp.add_handler(CommandHandler("mkdir", mkdir))
#admin functionalities #admin functionalities
dp.add_handler(CommandHandler("adduser", add_user)) dp.add_handler(CommandHandler("adduser", add_user))
dp.add_handler(CommandHandler("showuser", show_user)) dp.add_handler(CommandHandler("showuser", show_user))
dp.add_handler(CommandHandler("removeUser", remove_user)) dp.add_handler(CommandHandler("removeUser", remove_user))
dp.add_handler(CommandHandler("remove", remove)) dp.add_handler(CommandHandler("remove", remove))
dp.add_handler(CommandHandler("rmdir", rmdir)) dp.add_handler(CommandHandler("rmdir", rmdir))
# on noncommand i.e message - echo the message on Telegram # on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.document, echo)) dp.add_handler(MessageHandler(Filters.document, echo))
# log all errors # log all errors
dp.add_error_handler(error) dp.add_error_handler(error)
# Start the Bot # Start the Bot
updater.start_polling() updater.start_polling()
# Run the bot until you press Ctrl-C or the process receives SIGINT, # Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since # SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully. # start_polling() is non-blocking and will stop the bot gracefully.
updater.idle() updater.idle()
if __name__ == '__main__': if __name__ == '__main__':
main() main()

View File

@ -1 +1 @@
python-telegram-bot==10.1.0 python-telegram-bot==10.1.0

View File

@ -1,9 +1,9 @@
# Github_Bot # Github_Bot
A CLI tool to get github user and repository details. A CLI tool to get github user and repository details.
``` ```
>python main.py -f user -l username >python main.py -f user -l username
>python main.py -f repo -l username reponame >python main.py -f repo -l username reponame
``` ```
![](readme_assets/img.png) ![](readme_assets/img.png)

View File

@ -1,12 +1,12 @@
import PIL import PIL
from PIL import Image from PIL import Image
from tkinter.filedialog import * from tkinter.filedialog import *
file_path=askopenfilenames() file_path=askopenfilenames()
img = PIL.Image.open(file_path) img = PIL.Image.open(file_path)
myHeight,myWidth = img.size myHeight,myWidth = img.size
img=img.resize((myHeight,myWidth),PIL.Image.ANTILIAS) img=img.resize((myHeight,myWidth),PIL.Image.ANTILIAS)
save_path=asksaveasfile() save_path=asksaveasfile()
img.save(save_path+"_compressed.JPG") img.save(save_path+"_compressed.JPG")

View File

@ -1,20 +1,20 @@
# Keylogger # Keylogger
A script written in Python that logs your input from the keyboard. A script written in Python that logs your input from the keyboard.
### Steps to run this on terminal ### Steps to run this on terminal
- Clone the project. - Clone the project.
- Install the dependencies listed in requirements.txt. - Install the dependencies listed in requirements.txt.
- Run `python keylogger.py` in your terminal. - Run `python keylogger.py` in your terminal.
### PS ### PS
- You can use Delete key to exit the script. - You can use Delete key to exit the script.
- You can open log.txt to view your log. - You can open log.txt to view your log.
### Author ### Author
**[Preet Mishra](https://www.github.com/preetmishra)** **[Preet Mishra](https://www.github.com/preetmishra)**

View File

@ -1,13 +1,13 @@
astroid==2.1.0 astroid==2.1.0
autopep8==1.4.3 autopep8==1.4.3
certifi==2022.12.7 certifi==2022.12.7
colorama==0.4.1 colorama==0.4.1
isort==4.3.4 isort==4.3.4
lazy-object-proxy==1.3.1 lazy-object-proxy==1.3.1
mccabe==0.6.1 mccabe==0.6.1
pycodestyle==2.4.0 pycodestyle==2.4.0
pylint==2.2.2 pylint==2.2.2
pynput==1.4.4 pynput==1.4.4
six==1.12.0 six==1.12.0
wincertstore==0.2 wincertstore==0.2
wrapt==1.10.11 wrapt==1.10.11

View File

@ -1,26 +1,26 @@
# Importing the required packages. # Importing the required packages.
import PyPDF2 import PyPDF2
import pyttsx3 import pyttsx3
text = None text = None
# Reading a PDF file from your computer by specifying the path and setting the read mode to binary. # Reading a PDF file from your computer by specifying the path and setting the read mode to binary.
pdf_reader = PyPDF2.PdfFileReader(open(r"D:\MyPdf.pdf", "rb")) pdf_reader = PyPDF2.PdfFileReader(open(r"D:\MyPdf.pdf", "rb"))
# Getting the handle to speaker i.e. creating a reference to pyttsx3.Engine instance. # Getting the handle to speaker i.e. creating a reference to pyttsx3.Engine instance.
speaker = pyttsx3.init() speaker = pyttsx3.init()
# Splitting the PDF file into pages and reading one at a time. # Splitting the PDF file into pages and reading one at a time.
for page_number in range(pdf_reader.numPages): for page_number in range(pdf_reader.numPages):
text = pdf_reader.getPage(page_number).extractText() text = pdf_reader.getPage(page_number).extractText()
# Generating speech. # Generating speech.
speaker.say(text) speaker.say(text)
speaker.runAndWait() speaker.runAndWait()
# Stopping the speaker after the complete audio has been created. # Stopping the speaker after the complete audio has been created.
speaker.stop() speaker.stop()
# Saving the audiobook to your computer. # Saving the audiobook to your computer.
engine = pyttsx3.init() engine = pyttsx3.init()
engine.save_to_file(text, r"D:\MyAudio.mp3") engine.save_to_file(text, r"D:\MyAudio.mp3")
engine.runAndWait() engine.runAndWait()

View File

@ -1,2 +1,2 @@
PyPDF2 PyPDF2
pyttsx3 pyttsx3

View File

@ -177,7 +177,7 @@ So far, the following projects have been integrated to this repo:
|[Random_Email_Generator](Random_Email_Generator)|[Shubham Garg](https://github.com/shub-garg)| |[Random_Email_Generator](Random_Email_Generator)|[Shubham Garg](https://github.com/shub-garg)|
|[WiFi Password Viewer](Wifi-Password)|[Sagar Patel](https://github.com/sagar627)| |[WiFi Password Viewer](Wifi-Password)|[Sagar Patel](https://github.com/sagar627)|
|[Tambola_Ticket_Generator](Tambola_Ticket_Generator)|[Amandeep_Singh](https://github.com/Synster)| |[Tambola_Ticket_Generator](Tambola_Ticket_Generator)|[Amandeep_Singh](https://github.com/Synster)|
| [Py_Cleaner](Py_Cleaner) | [Abhishek Dobliyal](https://github.com/Abhishek-Dobliyal)| |[Py_Cleaner](Py_Cleaner) | [Abhishek Dobliyal](https://github.com/Abhishek-Dobliyal)|
|[Send messages to sqs in parallel](send_sqs_messages_in_parallel)|[Jinam Shah](https://github.com/jinamshah)| |[Send messages to sqs in parallel](send_sqs_messages_in_parallel)|[Jinam Shah](https://github.com/jinamshah)|
|[Codeforces Checker](codeforcesChecker)|[Jinesh Parakh](https://github.com/jineshparakh)| |[Codeforces Checker](codeforcesChecker)|[Jinesh Parakh](https://github.com/jineshparakh)|
|[Github repo creator](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/Git_repo_creator)|[Harish Tiwari ](https://github.com/optimist2309)| |[Github repo creator](https://github.com/hastagAB/Awesome-Python-Scripts/tree/master/Git_repo_creator)|[Harish Tiwari ](https://github.com/optimist2309)|

View File

@ -1,62 +1,62 @@
import random import random
import string import string
import csv import csv
import progressbar import progressbar
''' '''
Asks user for how many emails they want generated. Must be Integer. Asks user for how many emails they want generated. Must be Integer.
If not an integer, keeps recursively cycling back until it gets an integer. If not an integer, keeps recursively cycling back until it gets an integer.
''' '''
def getcount(): def getcount():
rownums = input("How many email addresses?: ") rownums = input("How many email addresses?: ")
try: try:
rowint = int(rownums) rowint = int(rownums)
return rowint return rowint
except ValueError: except ValueError:
print ("Please enter an integer value") print ("Please enter an integer value")
return getcount() return getcount()
''' '''
Creates a random string of digits between 1 and 20 characters alphanumeric and adds it to a fake domain and fake extension Creates a random string of digits between 1 and 20 characters alphanumeric and adds it to a fake domain and fake extension
Most of these emails are completely bogus (eg - gmail.gov) but will meet formatting requirements for my purposes Most of these emails are completely bogus (eg - gmail.gov) but will meet formatting requirements for my purposes
''' '''
def makeEmail(): def makeEmail():
extensions = ['com','net','org','gov'] extensions = ['com','net','org','gov']
domains = ['gmail','yahoo','comcast','verizon','charter','hotmail','outlook','frontier'] domains = ['gmail','yahoo','comcast','verizon','charter','hotmail','outlook','frontier']
winext = extensions[random.randint(0,len(extensions)-1)] winext = extensions[random.randint(0,len(extensions)-1)]
windom = domains[random.randint(0,len(domains)-1)] windom = domains[random.randint(0,len(domains)-1)]
acclen = random.randint(1,20) acclen = random.randint(1,20)
winacc = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(acclen)) winacc = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(acclen))
finale = winacc + "@" + windom + "." + winext finale = winacc + "@" + windom + "." + winext
return finale return finale
#save count to var #save count to var
howmany = getcount() howmany = getcount()
#counter for While loop #counter for While loop
counter = 0 counter = 0
#empty array for loop #empty array for loop
emailarray = [] emailarray = []
#uses counter to figure out how many emails to keep making #uses counter to figure out how many emails to keep making
print ("Creating email addresses...") print ("Creating email addresses...")
print ("Progress: ") print ("Progress: ")
prebar = progressbar.ProgressBar(maxval=int(howmany)) prebar = progressbar.ProgressBar(maxval=int(howmany))
for i in prebar(range(howmany)): for i in prebar(range(howmany)):
while counter < howmany: while counter < howmany:
emailarray.append(str(makeEmail())) emailarray.append(str(makeEmail()))
counter = counter+1 counter = counter+1
prebar.update(i) prebar.update(i)
print ("Creation completed.") print ("Creation completed.")
for i in emailarray: for i in emailarray:
print(i) print(i)

View File

@ -1,60 +1,60 @@
import random import random
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+`~[]{]\|;:,<.>/?' chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()-=_+`~[]{]\|;:,<.>/?'
welcomeMessage = "Welcome to the Password Generator!" welcomeMessage = "Welcome to the Password Generator!"
detailsMessage = "This program will generate a secure password using a random arrangement of letters (CAPS ON & caps off), numbers, and punctuations." detailsMessage = "This program will generate a secure password using a random arrangement of letters (CAPS ON & caps off), numbers, and punctuations."
creatorMessage = "Created by Professor Renderer on October 3rd, 2018." creatorMessage = "Created by Professor Renderer on October 3rd, 2018."
print(welcomeMessage + '\n' + detailsMessage + '\n' + creatorMessage + '\n') print(welcomeMessage + '\n' + detailsMessage + '\n' + creatorMessage + '\n')
exitMessage = 0 exitMessage = 0
passwordGeneratorUsage = 1 passwordGeneratorUsage = 1
passwordGeneratorPrompt = 1 passwordGeneratorPrompt = 1
while exitMessage != 1: while exitMessage != 1:
while passwordGeneratorUsage == 1: while passwordGeneratorUsage == 1:
passwordGeneratorPrompt = 1 passwordGeneratorPrompt = 1
passwordNum = input('How many passwords would you like to generate? ') passwordNum = input('How many passwords would you like to generate? ')
passwordNum = int(passwordNum) passwordNum = int(passwordNum)
passwordLength = input('How long will the password(s) be? ') passwordLength = input('How long will the password(s) be? ')
passwordLength = int(passwordLength) passwordLength = int(passwordLength)
print('\n') print('\n')
print('Here are your password(s): \n') print('Here are your password(s): \n')
passwordFile = open('Passwords.txt', 'w') passwordFile = open('Passwords.txt', 'w')
for p in range(passwordNum): for p in range(passwordNum):
password = '' password = ''
for c in range(passwordLength): for c in range(passwordLength):
password += random.choice(chars) password += random.choice(chars)
print(password) print(password)
passwordFile.write(password + '\n') passwordFile.write(password + '\n')
passwordFile.close() passwordFile.close()
print('\n') print('\n')
while passwordGeneratorPrompt == 1: while passwordGeneratorPrompt == 1:
getContinue = input('Do you want to use the Password Generator again? (Y/N)') getContinue = input('Do you want to use the Password Generator again? (Y/N)')
print('\n') print('\n')
if getContinue == "Y" or getContinue == "y": if getContinue == "Y" or getContinue == "y":
passwordGeneratorPrompt = 0 passwordGeneratorPrompt = 0
print('\n') print('\n')
elif getContinue == "N" or getContinue == "n": elif getContinue == "N" or getContinue == "n":
exitMessage = 1 exitMessage = 1
passwordGeneratorUsage = 0 passwordGeneratorUsage = 0
passwordGeneratorPrompt = 0 passwordGeneratorPrompt = 0
else: else:
print("Please enter 'Y' or 'N.'\n") print("Please enter 'Y' or 'N.'\n")
print('\n') print('\n')
print('Thank you for using the Password Generator. Have a nice day!') print('Thank you for using the Password Generator. Have a nice day!')

View File

@ -1,20 +1,20 @@
AaGhi>]!Tkz0{ik0S)mU<P@%6 AaGhi>]!Tkz0{ik0S)mU<P@%6
E|;>k7wuVdpSIkc:8V{q)e_*N E|;>k7wuVdpSIkc:8V{q)e_*N
!+B.C;YJ4+;/_$g>]FK/^vD]X !+B.C;YJ4+;/_$g>]FK/^vD]X
I[dgz&|>uoh(K:-i;xgE:F!!C I[dgz&|>uoh(K:-i;xgE:F!!C
$Ab\ag_?lD57,L]Gf3(]j04aw $Ab\ag_?lD57,L]Gf3(]j04aw
nCC&RS7K]]GK(%pDHr,>fyv?[ nCC&RS7K]]GK(%pDHr,>fyv?[
|VT3$kK5AGir))o9A6+ApR`%X |VT3$kK5AGir))o9A6+ApR`%X
:<Q/G13@Y2p4<rUz=Qj*^YSvZ :<Q/G13@Y2p4<rUz=Qj*^YSvZ
kP3Hk.=\bhjnk]ILD6Ek)MQFH kP3Hk.=\bhjnk]ILD6Ek)MQFH
+wIXDLOl(I[8|NRaBw=J&iT^1 +wIXDLOl(I[8|NRaBw=J&iT^1
wwly,3z;0X<-6kd>T<0],Kzm] wwly,3z;0X<-6kd>T<0],Kzm]
XVp,+V.ko[c/-C3M22*+p@J3> XVp,+V.ko[c/-C3M22*+p@J3>
zTR_S+lDuRn|MwGIVGFwu]pgH zTR_S+lDuRn|MwGIVGFwu]pgH
]p_8k1Z03$8]aJL@o^kY$#(Ez ]p_8k1Z03$8]aJL@o^kY$#(Ez
MGe:td4Ql~cZY&G.]u$IK){(p MGe:td4Ql~cZY&G.]u$IK){(p
/&1>(jI|SEdg*L6$Zz,NfetZp /&1>(jI|SEdg*L6$Zz,NfetZp
1dN6clgIgi-EfIYB@cn>#^mix 1dN6clgIgi-EfIYB@cn>#^mix
)cci)3*:0l$lNZ*Upi3ME?-C] )cci)3*:0l$lNZ*Upi3ME?-C]
<W2bM,E]PBQW%HE$sW1bwWDe! <W2bM,E]PBQW%HE$sW1bwWDe!
J^gQZ4.p%^|e>XC$#Rc*B+/Jr J^gQZ4.p%^|e>XC$#Rc*B+/Jr

View File

@ -1,29 +1,29 @@
# Programs # Programs
## [PasswordGenerator.py](./PasswordGenerator.py) ## [PasswordGenerator.py](./PasswordGenerator.py)
This program randomly generates a secure password using a mix of letters, both caps on and off, numbers, and punctuation, then outputs the results and saves them as a text document. This program randomly generates a secure password using a mix of letters, both caps on and off, numbers, and punctuation, then outputs the results and saves them as a text document.
## [createPassword.py](./createPassword.py) ## [createPassword.py](./createPassword.py)
This program uses the Python 3 module `secrets` to create a pseudo random password with alphanumeric, numbers, and special characters. The output will be printed into the terminal. This program uses the Python 3 module `secrets` to create a pseudo random password with alphanumeric, numbers, and special characters. The output will be printed into the terminal.
# Requirements # Requirements
* [PasswordGenerator.py](./PasswordGenerator.py) can use Python 3 and higher or Python 2 and higher * [PasswordGenerator.py](./PasswordGenerator.py) can use Python 3 and higher or Python 2 and higher
* [createPassword.py](./createPassword.py) can run on python 3.6 or higher or for Python 2 do: * [createPassword.py](./createPassword.py) can run on python 3.6 or higher or for Python 2 do:
* `cd Random_Password_Generator/` to change directory into this folder. * `cd Random_Password_Generator/` to change directory into this folder.
* Create virtual environment with `virtualvenv env` * Create virtual environment with `virtualvenv env`
* do `source venv/bin/activate` to activate virtual environment. * do `source venv/bin/activate` to activate virtual environment.
* do `pip install -r requirements.txt` to install python2-secrets * do `pip install -r requirements.txt` to install python2-secrets
* **TIP**: to deactivate virtual environment, do `deactivate`. * **TIP**: to deactivate virtual environment, do `deactivate`.
# Usage # Usage
For Windows users: For Windows users:
```bash ```bash
$ python PasswordGenerator.py $ python PasswordGenerator.py
``` ```
For Mac/Linux/Unix users: For Mac/Linux/Unix users:
```bash ```bash
$ ./PasswordGenerator.py $ ./PasswordGenerator.py
``` ```

0
SSH_Host_Adder/ssh_adder Executable file → Normal file
View File

View File

@ -1,3 +1,3 @@
author: Omar Sameh author: Omar Sameh
email: o.s.dr.who@gmail.com email: o.s.dr.who@gmail.com
no requirments enjoy! no requirments enjoy!

View File

@ -1,53 +1,53 @@
import random import random
board = [" "," "," "," "," "," "," "," "," "] board = [" "," "," "," "," "," "," "," "," "]
def display_board(): def display_board():
print("") print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ") print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ") print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ") print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("") print("")
def wincheck(mark): def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1 return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or (board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or (board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or (board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or (board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or (board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or (board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark )) (board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos): def make_turn(turn, pos):
if turn: if turn:
letter = "O" letter = "O"
else: else:
letter = "X" letter = "X"
board[pos-1] = letter board[pos-1] = letter
display_board() display_board()
turn = random.randint(0, 1) turn = random.randint(0, 1)
#display_board() #display_board()
print(""" print("""
board alignment: board alignment:
| 1 | 2 | 3 | | 1 | 2 | 3 |
| 4 | 5 | 6 | | 4 | 5 | 6 |
| 7 | 8 | 9 | | 7 | 8 | 9 |
""") """)
while True: while True:
if turn: if turn:
player = "O" player = "O"
else: else:
player = "X" player = "X"
pos= int(input(player + "'s turn: ")) pos= int(input(player + "'s turn: "))
if board[pos-1] != " ": if board[pos-1] != " ":
print("Taken, choose another") print("Taken, choose another")
continue continue
make_turn(turn, pos) make_turn(turn, pos)
if wincheck(player): if wincheck(player):
print(player + " wins!") print(player + " wins!")
break break
elif " " not in board: elif " " not in board:
print("Draw") print("Draw")
break break
turn = not turn turn = not turn
print("-" * 20) print("-" * 20)
input("") input("")

View File

@ -1,60 +1,60 @@
import random import random
def wincheck(board): def wincheck(board):
score = { score = {
"O": 1, "O": 1,
"X": -1 "X": -1
} }
for mark in ["O", "X"]: for mark in ["O", "X"]:
if ((board[0]==mark and board[1]== mark and board[2]==mark )or if ((board[0]==mark and board[1]== mark and board[2]==mark )or
(board[3]==mark and board[4]==mark and board[5]==mark )or (board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or (board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or (board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or (board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or (board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or (board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark )): (board[2]==mark and board[4]==mark and board[6]==mark )):
return score[mark] return score[mark]
if " " not in board: if " " not in board:
return 0 return 0
depth = [0] depth = [0]
def bestMove(board): def bestMove(board):
if depth[0] == 1: if depth[0] == 1:
return random.choice([i+1 for i in range(len(board)) if board[i] == " "]) return random.choice([i+1 for i in range(len(board)) if board[i] == " "])
best = float("inf") best = float("inf")
move = 0 move = 0
if board.count(" ") in [8, 9] and board[4] == " ": if board.count(" ") in [8, 9] and board[4] == " ":
return 5 return 5
for i in range(len(board)): for i in range(len(board)):
if board[i] == " ": if board[i] == " ":
board[i] = "X" board[i] = "X"
Try = findBestMove(board, 1, depth[0]) Try = findBestMove(board, 1, depth[0])
if Try < best: if Try < best:
best = Try best = Try
move = i move = i
board[i] = " " board[i] = " "
return move+1 return move+1
def findBestMove(board, maximizing, depth): def findBestMove(board, maximizing, depth):
if wincheck(board) is not None: if wincheck(board) is not None:
return wincheck(board) return wincheck(board)
if depth > 0: if depth > 0:
depth -= 1 depth -= 1
if maximizing == 1: if maximizing == 1:
best = float("-inf") best = float("-inf")
for i in range(len(board)): for i in range(len(board)):
if board[i] == " ": if board[i] == " ":
board[i] = "O" board[i] = "O"
Try = findBestMove(board, 0, depth) Try = findBestMove(board, 0, depth)
board[i] = " " board[i] = " "
best = max(best, Try) best = max(best, Try)
return best return best
if maximizing == 0: if maximizing == 0:
best = float("inf") best = float("inf")
for i in range(len(board)): for i in range(len(board)):
if board[i] == " ": if board[i] == " ":
board[i] = "X" board[i] = "X"
Try = findBestMove(board, 1, depth) Try = findBestMove(board, 1, depth)
board[i] = " " board[i] = " "
best = min(best, Try) best = min(best, Try)
return best return best
else: else:
return 0 return 0

View File

@ -1,67 +1,67 @@
import random import random
import TicTacToeAI import TicTacToeAI
depth = int(input( depth = int(input(
"""Choose difficulty: """Choose difficulty:
Easy: 1 Easy: 1
Medium: 2 Medium: 2
Hard: 3 Hard: 3
choice: """)) choice: """))
print(""" print("""
board alignment: board alignment:
| 1 | 2 | 3 | | 1 | 2 | 3 |
| 4 | 5 | 6 | | 4 | 5 | 6 |
| 7 | 8 | 9 | | 7 | 8 | 9 |
""") """)
TicTacToeAI.depth[0] = depth TicTacToeAI.depth[0] = depth
board = [" "," "," "," "," "," "," "," "," "] board = [" "," "," "," "," "," "," "," "," "]
def display_board(): def display_board():
print("") print("")
print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ") print("| "+board[0]+" | "+board[1]+" | "+board[2]+" | ")
print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ") print("| "+board[3]+" | "+board[4]+" | "+board[5]+" | ")
print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ") print("| "+board[6]+" | "+board[7]+" | "+board[8]+" | ")
print("") print("")
def wincheck(mark): def wincheck(mark):
return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1 return((board[0]==mark and board[1]== mark and board[2]==mark )or #for row1
(board[3]==mark and board[4]==mark and board[5]==mark )or (board[3]==mark and board[4]==mark and board[5]==mark )or
(board[6]==mark and board[7]==mark and board[8]==mark )or (board[6]==mark and board[7]==mark and board[8]==mark )or
(board[0]==mark and board[3]==mark and board[6]== mark )or (board[0]==mark and board[3]==mark and board[6]== mark )or
(board[1]==mark and board[4]==mark and board[7]==mark )or (board[1]==mark and board[4]==mark and board[7]==mark )or
(board[2]==mark and board[5]==mark and board[8]==mark )or (board[2]==mark and board[5]==mark and board[8]==mark )or
(board[0]==mark and board[4]==mark and board[8]==mark )or (board[0]==mark and board[4]==mark and board[8]==mark )or
(board[2]==mark and board[4]==mark and board[6]==mark )) (board[2]==mark and board[4]==mark and board[6]==mark ))
def make_turn(turn, pos): def make_turn(turn, pos):
if turn: if turn:
letter = "O" letter = "O"
else: else:
letter = "X" letter = "X"
board[pos-1] = letter board[pos-1] = letter
display_board() display_board()
turn = random.randint(0, 1) turn = random.randint(0, 1)
#display_board() #display_board()
while True: while True:
if turn: if turn:
player = "O" player = "O"
else: else:
player = "X" player = "X"
if player == "O": if player == "O":
pos= int(input(player + "'s turn: ")) pos= int(input(player + "'s turn: "))
else: else:
pos = TicTacToeAI.bestMove(board) pos = TicTacToeAI.bestMove(board)
if board[pos-1] != " ": if board[pos-1] != " ":
print("Taken, choose another") print("Taken, choose another")
continue continue
make_turn(turn, pos) make_turn(turn, pos)
if wincheck(player): if wincheck(player):
print(player + " wins!") print(player + " wins!")
break break
elif " " not in board: elif " " not in board:
print("Draw") print("Draw")
break break
turn = not turn turn = not turn
print("-" * 20) print("-" * 20)
input("") input("")

0
To Do Bot/Procfile Executable file → Normal file
View File

0
To Do Bot/README.md Executable file → Normal file
View File

0
To Do Bot/bot.py Executable file → Normal file
View File

0
To Do Bot/dbhelper.py Executable file → Normal file
View File

10
To Do Bot/requirements.txt Executable file → Normal file
View File

@ -1,5 +1,5 @@
python-dateutil==2.6.0 python-dateutil==2.6.0
requests requests
telepot==10.5 telepot==10.5
urllib3 urllib3
virtualenv==15.1.0 virtualenv==15.1.0

0
To Do Bot/runtime.txt Executable file → Normal file
View File

View File

@ -1,34 +1,34 @@
import argparse import argparse
import re import re
import requests import requests
def run(url: str) -> None: def run(url: str) -> None:
""" """
Detect all the URLs on a given website. Detect all the URLs on a given website.
:param url: the url of the website to process :param url: the url of the website to process
:return: :return:
""" """
# Load the website's HTML. # Load the website's HTML.
website = requests.get(url) website = requests.get(url)
html = website.text html = website.text
# Detect the URLs. # Detect the URLs.
URL_REGEX = r"http[s]?://(?:[a-zA-Z#]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+" URL_REGEX = r"http[s]?://(?:[a-zA-Z#]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
detected_urls = re.findall(URL_REGEX, html) detected_urls = re.findall(URL_REGEX, html)
# Filter invalid URLs. # Filter invalid URLs.
suffixes = "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw".split("|") suffixes = "aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|cz|de|dj|dk|dm|do|dz|ec|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mn|mn|mo|mp|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|nom|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ra|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw".split("|")
detected_urls = [x for x in detected_urls if any("."+suffix in x for suffix in suffixes)] detected_urls = [x for x in detected_urls if any("."+suffix in x for suffix in suffixes)]
print("\n".join(detected_urls)) print("\n".join(detected_urls))
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument( parser.add_argument(
"--website", "--website",
required=True, required=True,
help="URL of a website to detect other URLs on" help="URL of a website to detect other URLs on"
) )
args = parser.parse_args() args = parser.parse_args()
# Detect the URLs. # Detect the URLs.
run(args.website) run(args.website)

View File

@ -1,3 +1,3 @@
argparse argparse
re re
requests==2.31.0 requests==2.31.0

View File

@ -1,77 +1,77 @@
import argparse import argparse
from nltk.corpus import stopwords from nltk.corpus import stopwords
from nltk.probability import FreqDist from nltk.probability import FreqDist
from nltk.tokenize import word_tokenize from nltk.tokenize import word_tokenize
import re import re
import string import string
def preprocess(text: str) -> str: def preprocess(text: str) -> str:
""" """
Pre-process the input text. Pre-process the input text.
- Remove punctuation - Remove punctuation
- Remove numbers - Remove numbers
- Lowercase - Lowercase
:param text: text to pre-process :param text: text to pre-process
:return: the pre-processed text :return: the pre-processed text
""" """
# Lowercase. # Lowercase.
text = text.lower() text = text.lower()
# Remove numbers. # Remove numbers.
text = re.sub(r"[0-9]+", "", text) text = re.sub(r"[0-9]+", "", text)
# Remove punctuation. # Remove punctuation.
text = text.translate(str.maketrans("", "", string.punctuation)) text = text.translate(str.maketrans("", "", string.punctuation))
return text return text
def run(text: str) -> FreqDist: def run(text: str) -> FreqDist:
""" """
Count the word frequencies in a text. Count the word frequencies in a text.
The text is pre-processed beforehand to remove uninformative The text is pre-processed beforehand to remove uninformative
tokens such as punctuation, numbers, stopwords, and to unify tokens such as punctuation, numbers, stopwords, and to unify
the same tokens by lowercasing the text. the same tokens by lowercasing the text.
:param text: text to count the word frequencies in :param text: text to count the word frequencies in
:return: the word frequencies in the text :return: the word frequencies in the text
""" """
# Pre-process the text. # Pre-process the text.
text = preprocess(text) text = preprocess(text)
# Tokenize the text. # Tokenize the text.
tokens = word_tokenize(text) tokens = word_tokenize(text)
# Remove stopwords. # Remove stopwords.
stop_words = set(stopwords.words("english")) stop_words = set(stopwords.words("english"))
tokens = [token for token in tokens if token not in stop_words] tokens = [token for token in tokens if token not in stop_words]
# Count the frequencies. # Count the frequencies.
freq_dist = FreqDist(tokens) freq_dist = FreqDist(tokens)
print("Top 10 most frequent words:") print("Top 10 most frequent words:")
print(freq_dist.most_common(10)) print(freq_dist.most_common(10))
return freq_dist return freq_dist
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument( parser.add_argument(
"--filepath", "--filepath",
"-f", "-f",
required=True, required=True,
help="path to the text file" help="path to the text file"
) )
args = parser.parse_args() args = parser.parse_args()
# Open the text file. # Open the text file.
with open(args.filepath, "r") as f: with open(args.filepath, "r") as f:
text = f.read() text = f.read()
# Count the frequencies. # Count the frequencies.
freq_dist = run(text) freq_dist = run(text)
freq_dist_str = "\n".join([str(x) for x in freq_dist.most_common(freq_dist.B())]) freq_dist_str = "\n".join([str(x) for x in freq_dist.most_common(freq_dist.B())])
# Save the result. # Save the result.
old_file_name = args.filepath.split("/")[-1].split(".")[0] old_file_name = args.filepath.split("/")[-1].split(".")[0]
new_file_name = old_file_name + "_freq_dist" new_file_name = old_file_name + "_freq_dist"
new_filepath = args.filepath.replace(old_file_name, new_file_name) new_filepath = args.filepath.replace(old_file_name, new_file_name)
with open(new_filepath, "w") as f: with open(new_filepath, "w") as f:
f.write(freq_dist_str) f.write(freq_dist_str)
print(f"\nSaved the word frequencies to '{new_filepath}'") print(f"\nSaved the word frequencies to '{new_filepath}'")

View File

@ -1,4 +1,4 @@
argparse argparse
nltk==3.4.5 nltk==3.4.5
re re
string string

View File

@ -1,3 +1,3 @@
Once upon a time, a princess named Snow White lived in a castle with her father, the King, and her stepmother, the Queen. Her father had always said to his daughter that she must be fair to everyone at court. Said he, "People come here to the castle when they have a problem. They need the ruler to make a fair decision. Nothing is more important than to be fair." Once upon a time, a princess named Snow White lived in a castle with her father, the King, and her stepmother, the Queen. Her father had always said to his daughter that she must be fair to everyone at court. Said he, "People come here to the castle when they have a problem. They need the ruler to make a fair decision. Nothing is more important than to be fair."
The Queen, Snow White's stepmother, knew how much this meant to her husband. At the first chance, she went to her magic mirror. "Mirror, mirror, on the wall," said the Queen. "Who is the fairest of them all?" The Queen, Snow White's stepmother, knew how much this meant to her husband. At the first chance, she went to her magic mirror. "Mirror, mirror, on the wall," said the Queen. "Who is the fairest of them all?"

View File

@ -1,46 +1,46 @@
`Work log generator` `Work log generator`
-------------------- --------------------
📝 C'est quoi? 📝 C'est quoi?
=============== ===============
Ce simple script python permet de générer un journal de travail au format rst à partir des commits de l'un de vos dépôts. Ce simple script python permet de générer un journal de travail au format rst à partir des commits de l'un de vos dépôts.
🔘 Comment l'utiliser? 🔘 Comment l'utiliser?
======================= =======================
Il est nécessaire de commencer par générer un jeton d'accès et de l'entrer dans le premier champ de la fenêtre. Il est nécessaire de commencer par générer un jeton d'accès et de l'entrer dans le premier champ de la fenêtre.
Pour le générer, rendez-vous `ici`_ dans la section "Personal access tokens". Pour le générer, rendez-vous `ici`_ dans la section "Personal access tokens".
À présent, il est possible de presser sur le bouton de connexion. Dès lors, une liste déroulante affiche les dépôts disponibles. À présent, il est possible de presser sur le bouton de connexion. Dès lors, une liste déroulante affiche les dépôts disponibles.
Après le choix du dépôt, le dernier bouton permet d'ouvrir le log, de le modifier et de le sauvegarder au format rst. Après le choix du dépôt, le dernier bouton permet d'ouvrir le log, de le modifier et de le sauvegarder au format rst.
Il est maintenant possible de le convertir en utilisant pandoc ou n'importe quelle autre convertisseur que vous préférez. Il est maintenant possible de le convertir en utilisant pandoc ou n'importe quelle autre convertisseur que vous préférez.
Enjoy! Enjoy!
📝 What is this? 📝 What is this?
================ ================
This simple python script allows you to generate a worklog in rst format based on your repo commits. This simple python script allows you to generate a worklog in rst format based on your repo commits.
🔘 How to use it? 🔘 How to use it?
================= =================
Simply generate a personnal access token and enter it in the first field of the window. Simply generate a personnal access token and enter it in the first field of the window.
In order to generate this token, go `here`_ under "Personal access tokens". In order to generate this token, go `here`_ under "Personal access tokens".
Then, it is possible to press on the connection button. Since then a dropdown list display the available repositories. Then, it is possible to press on the connection button. Since then a dropdown list display the available repositories.
After choosing the repository, the last button allows you to open the log, edit it and save it in rst format. After choosing the repository, the last button allows you to open the log, edit it and save it in rst format.
You can then convert it using pandoc or any other converter you prefer. You can then convert it using pandoc or any other converter you prefer.
Enjoy! Enjoy!
.. _`ici`: https://github.com/settings/tokens .. _`ici`: https://github.com/settings/tokens
.. _`here`: https://github.com/settings/tokens .. _`here`: https://github.com/settings/tokens

0
caesar_cipher/caesar.py Executable file → Normal file
View File

0
git_automation/.my_commands.sh Executable file → Normal file
View File

0
git_automation/README.md Executable file → Normal file
View File

0
git_automation/create.py Executable file → Normal file
View File

0
git_automation/requirements.txt Executable file → Normal file
View File

View File

@ -1,3 +1,3 @@
meeting_id_1 meeting_id_1
meeting_id_2 meeting_id_2
meeting_id_3 meeting_id_3

View File

@ -1,3 +1,3 @@
meeting_time_1 meeting_time_1
meeting_time_2 meeting_time_2
meeting_time_3 meeting_time_3

View File

@ -1,2 +1,2 @@
PyAutoGUI==0.9.53 PyAutoGUI==0.9.53
schedule==1.1.0 schedule==1.1.0

View File

@ -1,12 +1,12 @@
# Instagram Video Downloader # Instagram Video Downloader
### Downlaods all the videos from instagram post. User needs to provide instagram post id as parameter ### Downlaods all the videos from instagram post. User needs to provide instagram post id as parameter
>> Example >> Example
``` ```
python instavideo.py B3NUFfmgRYW python instavideo.py B3NUFfmgRYW
``` ```
>> Example output file >> Example output file
``` ```
B3NUFfmgRYW_0.mp4 B3NUFfmgRYW_0.mp4
``` ```

View File

@ -1,38 +1,38 @@
import urllib.request import urllib.request
import requests import requests
import json import json
import re import re
import sys import sys
def download(post_id): def download(post_id):
multiple_posts = False multiple_posts = False
videos = [] videos = []
data = requests.get("https://instagram.com/p/{}".format(post_id)) data = requests.get("https://instagram.com/p/{}".format(post_id))
if data.status_code == 404: if data.status_code == 404:
print("Specified post not found") print("Specified post not found")
sys.exit() sys.exit()
json_data = json.loads(re.findall(r'window._sharedData\s=\s(\{.*\});</script>', data.text)[0]) json_data = json.loads(re.findall(r'window._sharedData\s=\s(\{.*\});</script>', data.text)[0])
data = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media'] data = json_data['entry_data']['PostPage'][0]['graphql']['shortcode_media']
if 'edge_sidecar_to_children' in data.keys(): if 'edge_sidecar_to_children' in data.keys():
multiple_posts = True multiple_posts = True
caption = data['edge_media_to_caption']['edges'][0]['node']['text'] caption = data['edge_media_to_caption']['edges'][0]['node']['text']
media_url = data['display_resources'][2]['src'] media_url = data['display_resources'][2]['src']
is_video = data['is_video'] is_video = data['is_video']
if not is_video and not multiple_posts: if not is_video and not multiple_posts:
print("No Videos found") print("No Videos found")
sys.exit() sys.exit()
if is_video: if is_video:
videos.append(data['video_url']) videos.append(data['video_url'])
if multiple_posts: if multiple_posts:
for post in data['edge_sidecar_to_children']['edges']: for post in data['edge_sidecar_to_children']['edges']:
if post['node']['is_video']: if post['node']['is_video']:
videos.append(post['node']['video_url']) videos.append(post['node']['video_url'])
print("Found total {} videos".format(len(videos))) print("Found total {} videos".format(len(videos)))
for no, video in zip(list(range(len(videos))), videos): for no, video in zip(list(range(len(videos))), videos):
print("Downloading video {}".format(no)) print("Downloading video {}".format(no))
urllib.request.urlretrieve(video, "{}_{}.mp4".format(post_id, no)) urllib.request.urlretrieve(video, "{}_{}.mp4".format(post_id, no))
if len(sys.argv) == 1: if len(sys.argv) == 1:
print("Please provide instagram post id") print("Please provide instagram post id")
else: else:
download(sys.argv[1]) download(sys.argv[1])

View File

@ -1 +1 @@
requests requests

0
mailing/gmail_messenger.py Executable file → Normal file
View File

View File

@ -1,2 +1,2 @@
random random
string string

View File

@ -1,24 +1,24 @@
import random import random
import string import string
def speak_like_yoda(sentence): def speak_like_yoda(sentence):
""" """
Translate the input sentence into Yoda-speak. Translate the input sentence into Yoda-speak.
:param sentence: input string :param sentence: input string
:return: translation to Yoda-speak :return: translation to Yoda-speak
""" """
sentence = sentence.lower() sentence = sentence.lower()
for p in string.punctuation.replace("'", ''): for p in string.punctuation.replace("'", ''):
sentence = sentence.replace(p, '') sentence = sentence.replace(p, '')
words = sentence.split() words = sentence.split()
random.shuffle(words) random.shuffle(words)
new_sent = ' '.join(words) new_sent = ' '.join(words)
print() print()
print('Your Yodenglish sentence:') print('Your Yodenglish sentence:')
print(new_sent.capitalize()) print(new_sent.capitalize())
if __name__ == '__main__': if __name__ == '__main__':
print('Your English sentence:') print('Your English sentence:')
sentence = str(input()) sentence = str(input())
speak_like_yoda(sentence) speak_like_yoda(sentence)

0
url_shortener/url_shortener.py Executable file → Normal file
View File