Sunday, December 11, 2022

Windows Logo in Python Turtle

from turtle import *


speed(1)

screensize()

screen = Screen()

screen.setup(900, 700)

bgcolor("#13143B")

color("#39d1ff")

penup()


goto(-300, 215)

pendown()

begin_fill()

goto(300, 300)

goto(300, -300)

goto(-300, -215)

goto(-300, 215)

end_fill()


color("#13143b")

width(25)

penup()

goto(-50, 300)

pendown()

goto(-50, -300)


penup()

goto(-305, 0)

pendown()

goto(305, -0)

hideturtle()

done()


Monday, July 25, 2022

Animation in tkinter



                              Space.png                                            UFO.png 

from tkinter import *

from time import sleep

from random import randint


WIDTH, HEIGHT = 500, 500

velX, velY = randint(-3, 3), randint(-3, 3)


win = Tk()

win.geometry("500x500")


canvas = Canvas(win, width=WIDTH, height=HEIGHT, bg="light blue")

canvas.place(x=0, y=0)


picSpace = PhotoImage(file="Space.png")

imgSpace = canvas.create_image(0, 0, image=picSpace, anchor=NW)


picUFO = PhotoImage(file="UFO.png")

imgUFO = canvas.create_image(10, 10, image=picUFO, anchor=NW)

imgWidth, imgHeight = picUFO.width(), picUFO.height()


running = True

while running:

  velX, velY = randint(-3, 3), randint(-3, 3)

  print(velX, velY)

  coordinates = canvas.coords(imgUFO)

  if(coordinates[0] >= (WIDTH - imgWidth) or coordinates[0] < 0):

    velX = -velX

  if(coordinates[1] >= (HEIGHT - imgHeight) or coordinates[1] < 0):

    velY = -velY

  canvas.move(imgUFO, velX, velY)

  win.update()

  sleep(0.003)

  

win.mainloop()

Friday, July 22, 2022

Python tkinter multiple animations (BroCode)

# https://youtu.be/qK8Pfll5ha8


from tkinter import *

from time import sleep


class Ball:

  def __init__(self, canvas, x, y, dia, xVel, yVel, color, outline):

    self.canvas = canvas

    self.image = canvas.create_oval(x, y, dia, dia, fill=color, outline=outline)

    self.xVel = xVel

    self.yVel = yVel


  def move(self):

    coordinates = self.canvas.coords(self.image)

    if (coordinates[2] >= (self.canvas.winfo_width()) or coordinates[0] < 0):

      self.xVel = -self.xVel

    if (coordinates[3] >= (self.canvas.winfo_height()) or coordinates[1] < 0):

      self.yVel = -self.yVel      

    self.canvas.move(self.image, self.xVel, self.yVel)


win = Tk()

win.geometry("500x500")


WIDTH, HEIGHT = 500, 500

canvas = Canvas(win, width=WIDTH, height=HEIGHT)

canvas.place(x=0, y=0)


volley_ball = Ball(canvas, 0, 0, 100, 1, 1, "black", "black")

tennis_ball = Ball(canvas, 0, 0,  50, 4, 3, "yellow", "white")

basket_ball = Ball(canvas, 0, 0, 125, 4, 3, "orange", "white")


while True:

  volley_ball.move()

  tennis_ball.move()

  basket_ball.move()

  win.update()

  sleep(0.01)

  

win.mainloop()


Saturday, July 9, 2022

Hardware Information Tool in Python (NeuralNine)

# https://youtu.be/_9ThkldEg0c

# pip install psutil

# pip install py-cpuinfo

# pip install wmi


import platform, psutil, cpuinfo, wmi


print(f"Architecture: {platform.architecture()}")

print(f"Network Name: {platform.node()}")

print(f"Operating Sys: {platform.platform()}")


print(f"Processor: {platform.processor()}")

my_cpuinfo = cpuinfo.get_cpu_info()

#print(my_cpuinfo.keys())

print(f"Full CPU Name: {my_cpuinfo['brand_raw']}")

print(f"Advertized CPU Name: {my_cpuinfo['hz_advertised_friendly']}")

print(f"Actual CPU Name: {my_cpuinfo['hz_actual_friendly']}")


print(f"RAM:{psutil.virtual_memory().total / (1024 ** 3): .2f} GB")

Wednesday, June 29, 2022

Create Index for text file (Idea from 9 Algorithms that changed the world - Google PageRank)

# Contents of Names.txt

Abdul Abdul Babu Geetha Joseph Leela Mary Mohammed Muhammed Suresh

Abdul Rajan Thomas Geetha Leela Mini Omana Rajesh Usha

Abdul Biju Fathima Geetha Muhammad Sindhu


filename = "Names.txt"

temp = "Temp.txt"


S = ''

def Eliminate(): # Add only alphabets, space & newline to string S

  inn = open(filename)

  s = inn.read()

  global S

  for i in s:

    if i.isalpha() or i == ' ' or i == '\n':

      S += i

    if i == '-':  # Hyphenated words become 2 words

      S += ' '

  inn.close()


def WriteToTemp(): # Write S to Temporary file

  out = open(temp, 'w')

  out.write(S)

  out.close()


def Indexing(): # 1st Indexing method

  Index = {}    # File index

  lineNo = 0

  inn = open(temp)

  

  while True:

    D = {}  # Line index

    line = inn.readline()

    if line == '':

      break

    lineNo += 1

    L = line.split()

    for word in L:  # Build line index

      if word in D.keys():

        D[word] += 1

      else:

        D[word] = 1


    for k, v in D.items():  # Use line index to

      if k in Index.keys(): # build file index

        Index[k].append(lineNo)

      else:

        Index[k] = [lineNo]


  for k, v in Index.items():

    print(k, v)


def Indexing(): # 2nd Indexing method

  lineNo = 0

  inn = open(temp)

  D = {}

  

  while True:

    line = inn.readline()

    if line == '':

      break

    lineNo += 1

    L = line.split()

    for word in L:  # Build index

      if word not in D.keys():

        D[word] = {lineNo}

      else:

        D[word].add(lineNo)


  for k, v in D.items():

    print(k, v)


Eliminate()

WriteToTemp()

Indexing()


Friday, June 24, 2022

Split Screen Videos with MoviePy (Neural Nine) (NeuralNine)

# https://www.youtube.com/watch?v=p293_8oYXL4

# pip install moviepy


from moviepy.editor import VideoFileClip, clips_array


clip1 = VideoFileClip("1.mp4").subclip(0, 5).margin(8) # From 0 secs

clip2 = VideoFileClip("2.mp4").subclip(0, 5).margin(8) # to 5 secs

clip3 = VideoFileClip("A.mp4").subclip(0, 5).margin(8) # Margin of 8

clip4 = VideoFileClip("D.mp4").subclip(0, 5).margin(8) # pixels


combined = clips_array([[clip1, clip2],

                                        [clip3, clip4]])

combined.write_videofile("Test.mp4")


Tuesday, June 21, 2022

Create & format MS-Word file in Python

# Create & format MS-Word file in Python

# https://www.youtube.com/watch?v=so2illANiRw


from docx import Document


doc = Document()

doc.add_heading("Hello World", 0)

doc.add_heading("Hello World")

doc.add_heading("Hello World", 2)

doc.add_heading("Hello World", 6)


p = doc.add_paragraph("Sample text")

p.add_run(" This text is bold.").bold = True

p.add_run(" This text is italicised.").italic = True


doc.add_paragraph("Item 1", style="List Bullet")

doc.add_paragraph("Item 2", style="List Bullet")

doc.add_paragraph("Item 3", style="List Bullet")


table_header = ["Name", "Age", "Job"]

data = [["John", 46, "Programmer"],

        ["Mary", 55, "Programmer"],

        ["Anna", 27, "Accountant"],

        ["Bob",  46, "Chef"]

       ]

table = doc.add_table(rows=1, cols=3)

for i in range(3):

  table.rows[0].cells[i].text = table_header[i]


for name, age, job in data:

  cells = table.add_row().cells

  cells[0].text = name

  cells[1].text = str(age)

  cells[2].text = job


doc.add_page_break()

doc.add_paragraph("Hello new page")

doc.add_picture("Thejus.png")


doc.save("Test.docx")

Saturday, June 4, 2022

Write text to image (Using textwrap) (LimeGuru)

# https://www.youtube.com/watch?v=g85jQfhG2MU


import cv2, textwrap


def put_text(img, text, x_value, y_value):

  font = cv2.FONT_HERSHEY_DUPLEX

  wrapped_text = textwrap.wrap(text, width=10)

  x, y = 200, 40

  font_size = 2

  font_thickness = 3


  for i, line in enumerate(wrapped_text):

    textsize = cv2.getTextSize(line, font, font_size, font_thickness)[0]

    gap = textsize[1] + 40

    y = y_value + i * gap

    x = int((img.shape[1] - textsize[0]) / 2)

    cv2.putText(img, line, (x_value, y), font, font_size,

                (255, 255, 255), font_thickness, lineType=cv2.LINE_AA)


img = cv2.imread("Image.jpg")

put_text(img, "Creative Minds Are Best", 80, 150)

cv2.imwrite("Output.jpg", img)


Tuesday, May 10, 2022

Playing Video and Audio in HTML

<Video controls> <source src="1961 Asterix the Gaul.mp4"> </Video>

<Audio controls> <source src="Kalimba.mp3"> </Audio>


Saturday, May 7, 2022

Screen Recorder in Python (NeuralNine)

# https://www.youtube.com/watch?v=08a3PikBSl8

import cv2, pyautogui, time

import numpy as np


SCREEN_SIZE = (1366, 768)

fourcc = cv2.VideoWriter_fourcc(*"XVID")

out = cv2.VideoWriter("output.avi", fourcc, 20.0, (SCREEN_SIZE))

fps, prev = 120, 0


while True:

  time_elapsed = time.time() - prev

  img = pyautogui.screenshot()

  if time_elapsed > 1.0 / fps:

    prev = time.time()

    frame = np.array(img)

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    out.write(frame)


  cv2.waitKey(5) # Changed 100 to 5 for proper capture


cv2.destroyAllWindows()

out.release()


Windows Notification in Python (NeuralNine)

# https://www.youtube.com/watch?v=5EHEG4gMCNs


from win10toast import ToastNotifier


toaster = ToastNotifier()

toaster.show_toast("Notification", "This is a message", duration=5)


Tuesday, April 19, 2022

View maps with tkintermapview

# https://www.youtube.com/watch?v=QvO4LTNDIyA


from tkinter import *

import tkintermapview


win = Tk()

win.title("Tkinter MapView")

win.geometry("900x700")


lbl1 = LabelFrame(win)

lbl1.pack(pady=20)


map_widget = tkintermapview.TkinterMapView(lbl1, width=800, height=600, corner_radius=0)

#map_widget.set_position(9.3346, 76.7077) # Kozhencherry

map_widget.set_zoom(20) # Max zoom


map_widget.set_address("Dilkusha Street, Kolkata 700017, West Bengal, India")

#map_widget.set_address("Thiruvalla Kumbazha Road, Kozhencherry, Kerala, India")

map_widget.pack()


win.mainloop()

Sunday, April 17, 2022

Convert images to movie (Using moviepy.editor)

# https://www.youtube.com/watch?v=X4Jw8egqGzI


from moviepy.editor import *


clips = []

clip1 = ImageClip("Koala.jpg").set_duration(1)

clip2 = ImageClip("Penguins.jpg").set_duration(2)

clip3 = ImageClip("Desert.jpg").set_duration(3)


clips.append(clip1)

clips.append(clip2)

clips.append(clip3)


video_clip = concatenate_videoclips(clips, method='compose')

video_clip.write_videofile("Video_output.mp4", fps=24, remove_temp=True, codec="libx264", audio_codec="aac")


Monday, April 4, 2022

Audio & Video editing with Python (MoviePy)

# https://www.youtube.com/watch?v=Q2d1tYvTjRw


from moviepy.editor import VideoFileClip, concatenate_videoclips, vfx

from moviepy.editor import AudioFileClip, afx, CompositeAudioClip


clip1 = VideoFileClip("1.mp4").subclip(0, 5)

clip2 = VideoFileClip("1.mp4").subclip(5, 10).fx(vfx.colorx, 1.5).fx(vfx.lum_contrast, 0, 50, 128)

clip3 = VideoFileClip("1.mp4").subclip(10, 15)

clip4 = VideoFileClip("1.mp4").subclip(15, 20).fx(vfx.colorx, 1.5).fx(vfx.lum_contrast, 0, 50, 128)

combined = concatenate_videoclips([clip1, clip2, clip3, clip4])

combined.write_videofile("Combined1.mp4")


clip1 = VideoFileClip("1.mp4").subclip(0, 5).fx(vfx.fadein, 1).fx(vfx.fadeout, 1)

clip2 = VideoFileClip("1.mp4").subclip(5, 10).fx(vfx.fadein, 1).fx(vfx.fadeout, 1)

clip3 = VideoFileClip("1.mp4").subclip(10, 15).fx(vfx.fadein, 1).fx(vfx.fadeout, 1)

clip4 = VideoFileClip("1.mp4").subclip(15, 20).fx(vfx.fadein, 1).fx(vfx.fadeout, 1)

combined = concatenate_videoclips([clip1, clip2, clip3, clip4])

combined.write_videofile("Combined2.mp4")


audio = AudioFileClip("1.mp3").fx(afx.audio_fadein, 1)  # Could pull audio from .mp4 also

combined = concatenate_videoclips([clip1, clip2, clip3, clip4])

combined.audio = CompositeAudioClip([audio])

combined.write_videofile("Combined.mp4")


Store Passwords Safely in Python (the bcrypt library)

Store Passwords Safely in Python (the bcrypt library)

When storing passwords, one of the greatest risks is that someone may steal the database and be able to decrypt them. To avoid this, you could hash the passwords before storing them. We need to install bcrpyt using pip: pip install bcrypt

It is good practice (although not required) to create a new virtual environment for this project. If you want to learn more about this, check How to Create and Manage Virtual Environments in Python

What is Password Hashing?

A hashing function is a function that takes a string of bytes, and “transforms” it to another string of bytes, from which it is impossible to determine the initial string. Furthermore, there aren’t two different inputs that give the same output. This means that if we store the hashed password, even if someone stole the database they would not be able to determine what the plain text passwords are.

Suppose a user has registered with the password "HelloWorld". To execute the login, we check if the password entered is the same as the stored one. To do so, we hash the password used for the login, and check if this hash corresponds to the stored one. Since by the definition there aren’t two different inputs that give the same output, the two hashes will be equal only if the password entered by the user is the same as the one used during registration.

The only weakness is that if the password is short, an attacker may try to hash all possible passwords until he finds the correct one. However, this is unlikely if the password is long enough since there are too many combinations. But how to make sure that the password is long? Usually, before hashing a password we will add a salt, i.e. a random sequence of characters. In this way, we know that even if the user uses a short password, it will still be secure.

Testing the Code

Here is the complete code of our PasswordDatabase:

import bcrypt

 

class PasswordDatabase:

  def __init__(self):

    self.data = dict()

  def register(self, user, password):

    if user in self.data:

      return False

    hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))

    self.data[user] = hashed

    return True

  def login(self, user, password):

    if user not in self.data:

      return False

    pwd_bytes = password.encode("utf-8")

    return bcrypt.checkpw(pwd_bytes, self.data[user])

# Driver code:

 

db = PasswordDatabase()

print("Registering users")

print(db.register("John", b"password"))

print(db.register("Seth", b"HelloWorld"))

print(db.register("John", b"myname"))   # False - John already exists

 

print("Logging in users")

print(db.login("Abc", "password"))

print(db.login("John", "pwd"))

print(db.login("John", "password"))     # True - matches password

Useful links:

Python bcrypt tutorial shows how to hash passwords in Python with the bcrypt library… zetcode.com

Hashing Passwords In Python: Bcrypt Tutorial with Examples | HackerNoon

Create Word Cloud (WordCloud) using Python



# https://youtu.be/vRbSnlRyJNQ

from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
import numpy as np
import matplotlib.pyplot as plt
import PIL.Image

#STOPWORDS.add("ABCD")  Add other words to be excluded
#print(STOPWORDS)
text = "Python is a high-level, general-purpose programming language. \
Its design philosophy emphasizes code readability, using significant \
indentation. Its language constructs & OOPs approach aim to help \
programmers write clear, logical code for small and large-scale projects. \
Python is dynamically-typed and garbage-collected. It supports multiple \
programming paradigms, including structured (particularly procedural), \
object-oriented and functional programming. It is often described as a \
\"batteries included\" language due to a comprehensive standard library. \
Guido van Rossum began working on Python in the 1980s as a successor to \
the ABC programming language and released it in 1991 as Python 0.9.0. \
Python 2.0 was released in 2000 and introduced new features such as list \
comprehensions, cycle-detecting garbage collection, reference counting, & \
Unicode support. Python 3, released in 2008, was a major revision that is \
not completely backward-compatible with earlier versions. Python 2 was \
discontinued with in 2020. Python consistently ranks as one of the most \
popular programming languages."

'''
wc = WordCloud(stopwords=STOPWORDS).generate(text)
plt.imshow(wc)
plt.axis("off")
plt.show()
'''

python_mask = np.array(PIL.Image.open("PythonLogo1.png"))
colormap = ImageColorGenerator(python_mask)
wc = WordCloud(stopwords=STOPWORDS, mask=python_mask,
               background_color="white", contour_color="black",
               contour_width=15, min_font_size=3,
               max_words=400).generate(text)
wc.recolor(color_func=colormap)
plt.imshow(wc)
plt.axis("off")
plt.show()

Tuesday, March 29, 2022

Sudoku from Tech with Tim

From: https://www.techwithtim.net/tutorials/python-programming/sudoku-solver-backtracking/

import pygame, time


pygame.font.init()


def solve(bo):

  find = find_empty(bo)

  if not find:

    return True

  else:

    row, col = find

  for i in range(1,10):

    if valid(bo, i, (row, col)):

      bo[row][col] = i

      if solve(bo):

        return True

      bo[row][col] = 0

  return False


def valid(bo, num, pos):

  for i in range(len(bo[0])):    # Check row

    if bo[pos[0]][i] == num and pos[1] != i:

      return False

  for i in range(len(bo)):       # Check column

    if bo[i][pos[1]] == num and pos[0] != i:

      return False

  box_x = pos[1] // 3            # Check box

  box_y = pos[0] // 3

  for i in range(box_y*3, box_y*3 + 3):

    for j in range(box_x * 3, box_x*3 + 3):

      if bo[i][j] == num and (i,j) != pos:

        return False

  return True


def print_boards(bo):

  for i in range(len(bo)):

    if i % 3 == 0 and i != 0:

      print("- - - - - - - - - - - - - ")

    for j in range(len(bo[0])):

      if j % 3 == 0 and j != 0:

        print(" | ", end="")

      if j == 8:

        print(bo[i][j])

      else:

        print(str(bo[i][j]) + " ", end="")


def find_empty(bo):

  for i in range(len(bo)):

    for j in range(len(bo[0])):

      if bo[i][j] == 0:

        return (i, j)  # row, col

  return None


class Grid:

  board = [[7, 8, 0, 4, 0, 0, 1, 2, 0],

           [6, 0, 0, 0, 7, 5, 0, 0, 9],

           [0, 0, 0, 6, 0, 1, 0, 7, 8],

           [0, 0, 7, 0, 4, 0, 2, 6, 0],

           [0, 0, 1, 0, 5, 0, 9, 3, 0],

           [9, 0, 4, 0, 6, 0, 0, 0, 5],

           [0, 7, 0, 3, 0, 0, 0, 1, 2],

           [1, 2, 0, 0, 0, 7, 4, 0, 0],

           [0, 4, 9, 2, 0, 6, 0, 0, 7]

          ]

  def __init__(self, rows, cols, width, height):

    self.rows = rows

    self.cols = cols

    self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]

    self.width = width

    self.height = height

    self.model = None

    self.selected = None


  def update_model(self):

    self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)]


  def place(self, val):

    row, col = self.selected

    if self.cubes[row][col].value == 0:

      self.cubes[row][col].set(val)

      self.update_model()

      if valid(self.model, val, (row,col)) and solve(self.model):

        return True

      else:

        self.cubes[row][col].set(0)

        self.cubes[row][col].set_temp(0)

        self.update_model()

        return False


  def sketch(self, val):

    row, col = self.selected

    self.cubes[row][col].set_temp(val)


  def draw(self, win):

    gap = self.width / 9          # Draw Grid Lines

    for i in range(self.rows+1):

      if i % 3 == 0 and i != 0:

        thick = 4

      else:

        thick = 1

      pygame.draw.line(win, (0,0,0), (0, i*gap), (self.width, i*gap), thick)

      pygame.draw.line(win, (0, 0, 0), (i * gap, 0), (i * gap, self.height), thick)

    for i in range(self.rows):    # Draw Cubes

      for j in range(self.cols):

        self.cubes[i][j].draw(win)


  def select(self, row, col):     # Reset all other

    for i in range(self.rows):

      for j in range(self.cols):

        self.cubes[i][j].selected = False

    self.cubes[row][col].selected = True

    self.selected = (row, col)


  def clear(self):

    row, col = self.selected

    if self.cubes[row][col].value == 0:

      self.cubes[row][col].set_temp(0)


  def click(self, pos):

    if pos[0] < self.width and pos[1] < self.height:

      gap = self.width / 9

      x = pos[0] // gap

      y = pos[1] // gap

      return (int(y), int(x))    # return: (col, row)

    else:

      return None


  def is_finished(self):

    for i in range(self.rows):

      for j in range(self.cols):

        if self.cubes[i][j].value == 0:

          return False

    return True


class Cube:

  rows, cols = 9, 9

  def __init__(self, value, row, col, width ,height):

    self.value = value

    self.temp = 0

    self.row = row

    self.col = col

    self.width = width

    self.height = height

    self.selected = False


  def draw(self, win):

    fnt = pygame.font.SysFont("comicsans", 40)

    gap = self.width / 9

    x = self.col * gap

    y = self.row * gap

    if self.temp != 0 and self.value == 0:

      text = fnt.render(str(self.temp), 1, (128,128,128))

      win.blit(text, (x+5, y+5))

    elif not(self.value == 0):

      text = fnt.render(str(self.value), 1, (0, 0, 0))

      win.blit(text, (x + (gap/2 - text.get_width()/2), y + (gap/2 - text.get_height()/2)))

    if self.selected:

      pygame.draw.rect(win, (255,0,0), (x,y, gap ,gap), 3)


  def set(self, val):

    self.value = val


  def set_temp(self, val):

    self.temp = val


def redraw_window(win, board, time, strikes):

  win.fill((255,255,255))

  fnt = pygame.font.SysFont("comicsans", 30)        # Draw time

  text = fnt.render("Time: " + format_time(time), 1, (0,0,0))

  win.blit(text, (200, 560))

  text = fnt.render("X " * strikes, 1, (255, 0, 0))  # Draw Strikes

  win.blit(text, (20, 560))

  board.draw(win)  # Draw grid and board


def format_time(secs):

  sec = secs%60

  minute = secs//60

  hour = minute//60

  mat = " " + str(minute) + ":" + str(sec)

  return mat


def main():

  win = pygame.display.set_mode((540,600))

  pygame.display.set_caption("Sudoku")

  board = Grid(9, 9, 540, 540)

  key = None

  run = True

  start = time.time()

  strikes = 0

  while run:

    play_time = round(time.time() - start)

    for event in pygame.event.get():

      if event.type == pygame.QUIT:

        run = False

      if event.type == pygame.KEYDOWN:

        if 49 <= event.key <= 57:  # Checking for digits 1 - 9

          key = event.key - 48

        if event.key == pygame.K_DELETE:

          board.clear()

          key = None

        if event.key == pygame.K_RETURN:

          i, j = board.selected

          if board.cubes[i][j].temp != 0:

            if board.place(board.cubes[i][j].temp):

              print("Success")

            else:

              print("Wrong")

              strikes += 1

            key = None

            if board.is_finished():

              print("Game over")

              run = False

      if event.type == pygame.MOUSEBUTTONDOWN:

        pos = pygame.mouse.get_pos()

        clicked = board.click(pos)

        if clicked:

          board.select(clicked[0], clicked[1])

          key = None

    if board.selected and key != None:

      board.sketch(key)

    redraw_window(win, board, play_time, strikes)

    pygame.display.update()


main()

pygame.quit()

Friday, March 11, 2022

Sentiment Analysis

# Positive_Words.py and Negative_Words.py saved in Drive\Resources

from Positive_Words import P

from Negative_Words import N


s1 = "It is easy to use. It took less than a week to understand where everything is in the software. Their customer success team is amazing and there's always someone available for their support team on live chat to help you."

s2 = "The mobile app can be really glitchy and is definitely not user friendly. AmericanAir just landed 3 hours late. Now twenty more minutes at the gate. I have patience but none for incompetence."

s3 = "I've had multiple conversations with your customer support team and they are absolutely worthless. No one has been able to address my issue or process the refund I was promised."

s4 = "There isn't enough focus on solving user problems. The foldable phone (more an expandable tablet), is nice for marketing, but doesn't address major user needs."

s5 = "I love how Zapier takes different apps and ties them together. I still need to further test Zapier to say if its useful for me or not. Zapier is so confusing to me."

s6 = "The older interface was much simpler. Awful experience. I would never buy this product again! I don't think there is anything I really dislike about the product."

s7 = "Hubspot makes my day a lot easier. Your customer service is a nightmare! Totally useless!!"

s = ''

punc = ".!?"


for i in s1:

  if i not in punc:

    s += i


L = s.split()

pos, neg = [], []


for i in L:

  if i in P:

    pos.append(i)

  if i in N:

    neg.append(i)


print(pos)

print(len(pos), "positives\n")

print(neg)

print(len(neg), "negatives")


Sliding game in Python

from random import shuffle, choice


L  = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, '']]

LL = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, '']]

arrow_keys = ["I", "L", "K", "J"]


def distribute():

  for ctr in range(1000):

    for i in range(4):

      flag = 0

      for j in range(4):

        if L[i][j] == '':

          r, c = i, j

          flag = 1

          break

      if flag == 1:

        break

    

    key = choice(arrow_keys)


    if key == 'I' and r != 3:

      L[r+1][c], L[r][c] = L[r][c], L[r+1][c]

    elif key == 'L' and c != 0:

      L[r][c-1], L[r][c] = L[r][c], L[r][c-1]

    elif key == 'K' and r != 0:

      L[r][c], L[r-1][c] = L[r-1][c], L[r][c]

    elif key == 'J' and c != 3:

      L[r][c+1], L[r][c] = L[r][c], L[r][c+1]


def display():

  print("/===========================\\")

  print("|      |      |      |      |")

  print("|  %2s  |  %2s  |  %2s  |  %2s  |" % (L[0][0], L[0][1], L[0][2], L[0][3]))

  print("|      |      |      |      |")

  print("|======|======|======|======|")

  print("|      |      |      |      |")

  print("|  %2s  |  %2s  |  %2s  |  %2s  |" % (L[1][0], L[1][1], L[1][2], L[1][3]))

  print("|      |      |      |      |")

  print("|======|======|======|======|")

  print("|      |      |      |      |")

  print("|  %2s  |  %2s  |  %2s  |  %2s  |" % (L[2][0], L[2][1], L[2][2], L[2][3]))

  print("|      |      |      |      |")

  print("|======|======|======|======|")

  print("|      |      |      |      |")

  print("|  %2s  |  %2s  |  %2s  |  %2s  |" % (L[3][0], L[3][1], L[3][2], L[3][3]))

  print("|      |      |      |      |")

  print("\===========================/")


def play():

  while LL != L:

    r, c = 0, 0

  

    for i in range(4):

      flag = 0

      for j in range(4):

        if L[i][j] == '':

          r, c = i, j

          flag = 1

          break

      if flag == 1:

        break


    key = input().upper()


    if key == 'I' and r != 3:

      L[r+1][c], L[r][c] = L[r][c], L[r+1][c]

    elif key == 'L' and c != 0:

      L[r][c-1], L[r][c] = L[r][c], L[r][c-1]

    elif key == 'K' and r != 0:

      L[r][c], L[r-1][c] = L[r-1][c], L[r][c]

    elif key == 'J' and c != 3:

      L[r][c+1], L[r][c] = L[r][c], L[r][c+1]

    

    display()

  print("You won!!")


distribute()

display()

play()


Thursday, February 17, 2022

# Randomly display 5 cards

# Cards stored in Google Drive under Resources

from tkinter import *

import random


win = Tk()

win.geometry("800x600")


def pick():

  txt.delete(1.0, END)

  txt.insert(END, '          PICKING 5 CARDS AT RANDOM\n\n')

  Keys = list(d.keys())

  random.shuffle(Keys)

  Chosen = Keys[:5]


  for i in range(5):

    txt.insert(END, str(Chosen[i]) + '\t' + str(d[Chosen[i]]) + '\n')

    stgImg = PhotoImage(file=str(Chosen[i]) + ".png")

    eval(("lbl") + str(i+1)).configure(image=stgImg)

    eval(("lbl") + str(i+1)).image = stgImg


d = {}

suites = ['Hearts', 'Spades', 'Diamonds', 'Clubs']

numbers = ['Ace'] + list(range(2, 11)) + ['Jack', 'Queen', 'King']

ctr = 1


for i in suites:

  for j in numbers:

    d[ctr] = str(j) + " of " + i

    ctr += 1


btn = Button(win, text='Pick 5 Cards', font=('calibri', 15), fg='green', bg='black', command=pick)

btn.place(x=40, y=10)


txt = Text(win, width=35, height=7, font=('Verdana', 16))

txt.place(x=200, y=10)


lbl1 = Label(win);  lbl1.place(x=130, y=400)

lbl2 = Label(win);  lbl2.place(x=230, y=400)

lbl3 = Label(win);  lbl3.place(x=330, y=400)

lbl4 = Label(win);  lbl4.place(x=430, y=400)

lbl5 = Label(win);  lbl5.place(x=530, y=400)


win.mainloop()


Tuesday, February 8, 2022

Detecting ARROW KEY and other NON-PRINTING KEY presses in Python IDLE

# pip install pynput


from pynput.keyboard import Key, Listener


def on_press(key):

  print('{0} pressed'.format(key))

  print(key)

  if key == Key.up:

    print("Up")

  elif key == Key.right:

    print("Right")

  elif key == Key.down:

    print("Down")

  elif key == Key.left:

    print("Left")


def on_release(key):

  print('{0} release'.format(key))

  if key == Key.esc:

    return False  # Stop listener


# Collect events until released

with Listener(on_press=on_press, on_release=on_release) as listener:

  listener.join()


Wednesday, February 2, 2022

Wordle in Python

# Bug: If word is AUGHT and AMAZE is entered, output is AMAZE, i.e., 'A' in 2 positions.

from clrprint import clrprint

import random

L = ['ABACK', 'ABAFT', 'ABOUT', 'ABOVE', 'ACUTE', 'ADIEU', 'ADIOS', 'ADMIT',

     'ADOPT', 'ADULT', 'AFOOT', 'AFORE', 'AFOUL', 'AFTER', 'AGAIN', 'AGAPE',

     'AGENT', 'AGREE', 'AHEAD', 'ALACK', 'ALIKE', 'ALIVE', 'ALLOW', 'ALOFT',

     'ALONE', 'ALONG', 'ALOOF', 'ALOUD', 'ALTER', 'AMISS', 'AMONG', 'AMPLY',

     'AMUCK', 'ANGER', 'ANGRY', 'APACE', 'APART', 'APPLE', 'APPLY', 'APTLY',

     'AREAR', 'ARGUE', 'ARISE', 'ASIDE', 'ASKEW', 'AUGHT', 'AVOID', 'AWARD',

     'AWARE', 'AWFUL', 'BADLY', 'BALLY', 'BASIC', 'BASIS', 'BEACH', 'BEGIN',

     'BELOW', 'BIRTH', 'BLACK', 'BLAME', 'BLESS', 'BLIND', 'BLOCK', 'BLOOD',

     'BOARD', 'BOTHE', 'BRAIN', 'BRAVE', 'BRAVO', 'BREAD', 'BREAK', 'BRIEF',

     'BRING', 'BROAD', 'BROWN', 'BUILD', 'BURST', 'BUYER', 'CANNY', 'CARRY',

     'CATCH', 'CAUSE', 'CHAIN', 'CHAIR', 'CHEAP', 'CHECK', 'CHEST', 'CHIEF',

     'CHILD', 'CHINA', 'CIRCA', 'CIVIL', 'CLAIM', 'CLASS', 'CLEAN', 'CLEAR',

     'CLIMB', 'CLOCK', 'CLOSE', 'COACH', 'COAST', 'COUNT', 'COURT', 'COVER',

     'COYLY', 'CRAZY', 'CREAM', 'CRIME', 'CROSS', 'CROWD', 'CROWN', 'CYCLE',

     'DAILY', 'DANCE', 'DEATH', 'DEPTH', 'DIMLY', 'DIRTY', 'DITTO', 'DOUBT',

     'DRAFT', 'DRAMA', 'DREAM', 'DRESS', 'DRINK', 'DRIVE', 'DRYLY', 'DULLY',

     'EARLY', 'EARTH', 'EMPTY', 'ENEMY', 'ENJOY', 'ENTER', 'ENTRY', 'EQUAL',

     'ERROR', 'EVENT', 'EXACT', 'EXIST', 'EXTRA', 'FAINT', 'FAITH', 'FALSE',

     'FATLY', 'FAULT', 'FIELD', 'FIFTH', 'FIGHT', 'FINAL', 'FIRST', 'FLOOR',

     'FOCUS', 'FORCE', 'FORTE', 'FORTH', 'FRAME', 'FRANK', 'FRESH', 'FRONT',

     'FRUIT', 'FUDGE', 'FULLY', 'FUNNY', 'GAILY', 'GIANT', 'GLASS', 'GODLY',

     'GOLLY', 'GRAND', 'GRANT', 'GRASS', 'GREAT', 'GREEN', 'GROSS', 'GROUP',

     'GUESS', 'GUIDE', 'HAPPY', 'HARSH', 'HAVOC', 'HEART', 'HEAVY', 'HELLA',

     'HELLO', 'HENCE', 'HENRY', 'HORSE', 'HOTEL', 'HOTLY', 'HOUSE', 'HOWDY',

     'HUMAN', 'ICILY', 'IDEAL', 'IMAGE', 'IMPLY', 'INDEX', 'INFRA', 'INNER',

     'INPUT', 'ISSUE', 'JAPAN', 'JOINT', 'JOLLY', 'JONES', 'JUDGE', 'KNIFE',

     'LARGE', 'LAUGH', 'LAYER', 'LEARN', 'LEAVE', 'LEGAL', 'LEVEL', 'LIGHT',

     'LIMIT', 'LOCAL', 'LOOSE', 'LOWLY', 'LUCKY', 'LUNCH', 'MADLY', 'MAGIC',

     'MAJOR', 'MARCH', 'MARRY', 'MATCH', 'MAYBE', 'MERCY', 'METAL', 'MINOR',

     'MINUS', 'MODEL', 'MONEY', 'MONTH', 'MORAL', 'MOTOR', 'MOUTH', 'MUSIC',

     'NAKED', 'NASTY', 'NAVAL', 'NEATH', 'NEVER', 'NEWLY', 'NIGHT', 'NOBLY',

     'NOISE', 'NORTH', 'NOVEL', 'NURSE', 'OCCUR', 'ODDLY', 'OFFER', 'OFTEN',

     'ORDER', 'OTHER', 'OUGHT', 'OUTER', 'OWNER', 'PANEL', 'PAPER', 'PARTY',

     'PEACE', 'PHASE', 'PHONE', 'PIANO', 'PIECE', 'PILOT', 'PITCH', 'PLACE',

     'PLAIN', 'PLANE', 'PLANT', 'PLATE', 'PLONK', 'PLUMB', 'POINT', 'POUND',

     'POWER', 'PRESS', 'PRICE', 'PRIDE', 'PRIME', 'PRIOR', 'PRIZE', 'PROOF',

     'PROUD', 'PROVE', 'QUEEN', 'QUEER', 'QUICK', 'QUIET', 'QUITE', 'RADIO',

     'RAISE', 'RANGE', 'RAPID', 'RATIO', 'REACH', 'READY', 'REFER', 'RELAX',

     'REPLY', 'RIGHT', 'RIVER', 'ROMAN', 'ROUGH', 'ROUND', 'ROUTE', 'ROYAL',

     'RUGBY', 'RURAL', 'SADLY', 'SALVE', 'SCALE', 'SCENE', 'SCOPE', 'SCORE',

     'SENSE', 'SERVE', 'SHALL', 'SHAPE', 'SHARE', 'SHARP', 'SHEEP', 'SHEER',

     'SHEET', 'SHIFT', 'SHIRT', 'SHOCK', 'SHOOT', 'SHORT', 'SHYLY', 'SIGHT',

     'SILLY', 'SINCE', 'SIXTH', 'SKILL', 'SLASH', 'SLEEK', 'SLEEP', 'SLYLY',

     'SMALL', 'SMART', 'SMILE', 'SMOKE', 'SNIFF', 'SOLID', 'SOLVE', 'SORRY',

     'SOUND', 'SOUTH', 'SPACE', 'SPARE', 'SPEAK', 'SPEED', 'SPEND', 'SPITE',

     'SPLIT', 'SPORT', 'SQUAD', 'STAFF', 'STAGE', 'STAND', 'STARK', 'START',

     'STATE', 'STEAM', 'STEEL', 'STEEP', 'STICK', 'STILL', 'STOCK', 'STONE',

     'STORE', 'STUDY', 'STUFF', 'STYLE', 'SUGAR', 'SUPER', 'SWEET', 'TABLE',

     'TALLY', 'TASTE', 'TEACH', 'TERRY', 'THANK', 'THEME', 'THERE', 'THICK',

     'THINE', 'THING', 'THINK', 'THIRD', 'THROW', 'TIGHT', 'TITLE', 'TODAY',

     'TOTAL', 'TOUCH', 'TOUGH', 'TOWER', 'TRACK', 'TRADE', 'TRAIN', 'TREAT',

     'TREND', 'TRIAL', 'TRULY', 'TRUST', 'TRUTH', 'TWICE', 'TWIRP', 'UNCLE',

     'UNDER', 'UNION', 'UNITY', 'UNTIL', 'UPPER', 'UPSET', 'URBAN', 'USUAL',

     'UTTER', 'VAGUE', 'VALID', 'VALUE', 'VIDEO', 'VIOLA', 'VISIT', 'VITAL',

     'VOICE', 'WASTE', 'WATCH', 'WATER', 'WETLY', 'WHERE', 'WHICH', 'WHILE',

     'WHIST', 'WHITE', 'WHOLE', 'WHOSE', 'WOMAN', 'WORLD', 'WORRY', 'WOULD',

     'WRITE', 'WRONG', 'WRYLY', 'YOUNG', 'YOURS', 'YOUTH']


word = "AUGHT"#random.choice(L)

ctr = 1


while ctr < 10:

  try:

    guess = input("Guess a 5 letter word: ").upper()

    for i in range(5):

      if guess[i] == word[i]:

        clrprint(guess[i], clr='g', end='')

      elif guess[i] in word:

        clrprint(guess[i], clr='b', end='')

      else:

        clrprint(guess[i], clr='r', end='')

    print()

  except: 

    clrprint("\nYour word must have exactly 5 letters", clr='r')

  

  if word == guess:

    print("CONGRATS!! Got it in", ctr, "tries.")

    break

  ctr += 1

else:

  print("SORRY!! The word was", word)

Sunday, January 30, 2022

Simulating the throw of a die / dice in Python IDLE text mode

from random import randint


def die1():

  print()

  print(" ----- ")

  print("|     |")

  print("|  O  |")

  print("|     |")

  print(" ----- ")


def die2():

  print()

  print(" ----- ")

  print("|  O  |")

  print("|     |")

  print("|  O  |")

  print(" ----- ")


def die3():

  print()

  print(" ----- ")

  print("|O    |")

  print("|  O  |")

  print("|    O|")

  print(" ----- ")


def die4():

  print()

  print(" ----- ")

  print("| O O |")

  print("|     |")

  print("| O O |")

  print(" ----- ")


def die5():

  print()

  print(" ----- ")

  print("|O   O|")

  print("|  O  |")

  print("|O   O|")

  print(" ----- ")


def die6():

  print()

  print(" ----- ")

  print("|O O O|")

  print("|     |")

  print("|O O O|")

  print(" ----- ")


for i in range(10):

  num = randint(1, 6)

  eval("die" + str(num) + "()")

  input()