diff --git a/Brain Teaser Game/README.md b/Brain Teaser Game/README.md new file mode 100644 index 0000000000..f8797ee549 --- /dev/null +++ b/Brain Teaser Game/README.md @@ -0,0 +1,69 @@ +# Brain Teaser Game + +This repository contains a simple brain teaser game implemented in Python. The game presents a series of brain teasers, and the player must provide answers to each one. If the player's answer matches the correct answer, they score a point. The game is a fun way to challenge your brain and test your lateral thinking skills. + +## How to Play + +1. Clone this repository to your local machine: + + ```bash + git clone https://github.com/your-username/brain-teaser-game.git + ``` + +2. Navigate to the repository's directory: + + ```bash + cd brain-teaser-game + ``` + +3. Run the game using your Python interpreter: + + ```bash + python brain_teaser_game.py + ``` + +4. The game will present you with a series of brain teasers, and you'll be prompted to provide your answers. Answer as many questions as you can to score points. + +## Brain Teasers Included + +The game includes the following brain teasers: + +1. "I speak without a mouth and hear without ears. I have no body, but I come alive with the wind. What am I?" + - Correct Answer: an echo + +2. "What comes once in a minute, twice in a moment, but never in a thousand years?" + - Correct Answer: the letter 'm' + +3. "The more you take, the more you leave behind. What am I?" + - Correct Answer: footsteps + +4. "What has keys but can't open locks?" + - Correct Answer: a piano + +5. "You see a boat filled with people. It has not sunk, but when you look again you don’t see a single person on the boat. Why?" + - Correct Answer: all the people were married + +## Gameplay Example + +``` +Welcome to the Brain Teaser Game! +Try to answer the following brain teasers: + +Question: I speak without a mouth and hear without ears. I have no body, but I come alive with the wind. What am I? +Your Answer: wind +Sorry, the correct answer is 'an echo'. + +Question: What comes once in a minute, twice in a moment, but never in a thousand years? +Your Answer: m +Correct! + +Question: The more you take, the more you leave behind. What am I? +Your Answer: time +Sorry, the correct answer is 'footsteps'. + +Game Over! Your final score: 1 +``` + +## Customization + +Feel free to customize the `brain_teasers` list by adding more brain teasers or changing the questions and answers. You can enhance the game further by adding features like a timer, different difficulty levels, or a graphical user interface (GUI). diff --git a/Brain Teaser Game/script.py b/Brain Teaser Game/script.py new file mode 100644 index 0000000000..c16bdef325 --- /dev/null +++ b/Brain Teaser Game/script.py @@ -0,0 +1,32 @@ +import random + +# Define a list of brain teasers as tuples (question, answer) +brain_teasers = [ + ("I speak without a mouth and hear without ears. I have no body, but I come alive with the wind. What am I?", "an echo"), + ("What comes once in a minute, twice in a moment, but never in a thousand years?", "the letter 'm'"), + ("The more you take, the more you leave behind. What am I?", "footsteps"), + ("What has keys but can't open locks?", "a piano"), + ("You see a boat filled with people. It has not sunk, but when you look again you don’t see a single person on the boat. Why?", "all the people were married"), +] + +def play_game(): + score = 0 + random.shuffle(brain_teasers) # Shuffle the brain teasers for a random order + + print("Welcome to the Brain Teaser Game!") + print("Try to answer the following brain teasers:\n") + + for question, answer in brain_teasers: + print("Question:", question) + player_answer = input("Your Answer: ").lower() + + if player_answer == answer: + print("Correct!\n") + score += 1 + else: + print(f"Sorry, the correct answer is '{answer}'.\n") + + print("Game Over! Your final score:", score) + +if __name__ == "__main__": + play_game() diff --git a/ChatBot using OpenAI API/README.md b/ChatBot using OpenAI API/README.md new file mode 100644 index 0000000000..2a0da51c6d --- /dev/null +++ b/ChatBot using OpenAI API/README.md @@ -0,0 +1,61 @@ + +```markdown +# OpenAI Chatbot Example + +This repository contains examples of using the OpenAI GPT-3 model to create a chatbot that can hold conversations with users. + +## Prerequisites + +- OpenAI Python Package (`openai`) +- `requests` library (for Method 2) + +You can install the required libraries using the following commands: + +```bash +pip install openai requests +``` + +## Method 1 - Using OpenAI Python Package + +This method demonstrates how to use the OpenAI Python package to create a chatbot using the `gpt-3.5-turbo` model. + +The code provided in the repository (`method_1_openai_package.py`) includes: + +- Setting up the OpenAI API key. +- Initiating a conversation with a system message. +- Taking user inputs and generating replies using the chatbot. +- Displaying the chat history. + +## Method 2 - Using API Endpoint + +This method demonstrates how to interact with the OpenAI API directly using HTTP requests. + +The code provided in the repository (`method_2_api_endpoint.py`) includes: + +- Defining the API endpoint URL. +- Creating a payload with user inputs and other parameters. +- Sending a POST request to the API endpoint. +- Extracting and displaying the generated response. + +## Usage + +1. Set up your OpenAI API key by replacing `'sk-'` in the code with your actual API key. + +2. Choose the method you want to use (Method 1 or Method 2). + +3. Run the selected script using a Python interpreter: + + ```bash + python method_1_openai_package.py + ``` + or + ```bash + python method_2_api_endpoint.py + ``` + +4. Observe the interaction with the chatbot and the generated responses. + +## Notes + +- Make sure to review the OpenAI API documentation for more information on available models, parameters, and best practices. + diff --git a/ChatBot using OpenAI API/script1.ipynb b/ChatBot using OpenAI API/script1.ipynb new file mode 100644 index 0000000000..737378976b --- /dev/null +++ b/ChatBot using OpenAI API/script1.ipynb @@ -0,0 +1,90 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "!pip install -q openai" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "import openai" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "openai.api_key = 'sk-'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "messages = [\n", + " {\"role\": \"system\", \"content\": \"You are a kind helpful assistant.\"},\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + " message = input(\"User : \")\n", + " if message:\n", + " messages.append(\n", + " {\"role\": \"user\", \"content\": message},\n", + " )\n", + " chat = openai.ChatCompletion.create(\n", + " model=\"gpt-3.5-turbo\", messages=messages\n", + " )\n", + " \n", + " reply = chat.choices[0].message.content\n", + " print(f\"ChatGPT: {reply}\")\n", + " messages.append({\"role\": \"assistant\", \"content\": reply})\n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/ChatBot using OpenAI API/script2.ipynb b/ChatBot using OpenAI API/script2.ipynb new file mode 100644 index 0000000000..f11523833d --- /dev/null +++ b/ChatBot using OpenAI API/script2.ipynb @@ -0,0 +1,96 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'openai' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[1], line 18\u001b[0m\n\u001b[0;32m 3\u001b[0m URL \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mhttps://api.openai.com/v1/chat/completions\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m 5\u001b[0m payload \u001b[39m=\u001b[39m {\n\u001b[0;32m 6\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mmodel\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39mgpt-3.5-turbo\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[0;32m 7\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mmessages\u001b[39m\u001b[39m\"\u001b[39m: [{\u001b[39m\"\u001b[39m\u001b[39mrole\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39muser\u001b[39m\u001b[39m\"\u001b[39m, \u001b[39m\"\u001b[39m\u001b[39mcontent\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mWhat is the first computer in the world?\u001b[39m\u001b[39m\"\u001b[39m}],\n\u001b[1;32m (...)\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mfrequency_penalty\u001b[39m\u001b[39m\"\u001b[39m:\u001b[39m0\u001b[39m,\n\u001b[0;32m 14\u001b[0m }\n\u001b[0;32m 16\u001b[0m headers \u001b[39m=\u001b[39m {\n\u001b[0;32m 17\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mContent-Type\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39m\"\u001b[39m\u001b[39mapplication/json\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[1;32m---> 18\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mAuthorization\u001b[39m\u001b[39m\"\u001b[39m: \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mBearer \u001b[39m\u001b[39m{\u001b[39;00mopenai\u001b[39m.\u001b[39mapi_key\u001b[39m}\u001b[39;00m\u001b[39m\"\u001b[39m\n\u001b[0;32m 19\u001b[0m }\n\u001b[0;32m 21\u001b[0m response \u001b[39m=\u001b[39m requests\u001b[39m.\u001b[39mpost(URL, headers\u001b[39m=\u001b[39mheaders, json\u001b[39m=\u001b[39mpayload, stream\u001b[39m=\u001b[39m\u001b[39mFalse\u001b[39;00m)\n", + "\u001b[1;31mNameError\u001b[0m: name 'openai' is not defined" + ] + } + ], + "source": [ + "import requests\n", + "\n", + "URL = \"https://api.openai.com/v1/chat/completions\"\n", + "\n", + "payload = {\n", + "\"model\": \"gpt-3.5-turbo\",\n", + "\"messages\": [{\"role\": \"user\", \"content\": f\"What is the first computer in the world?\"}],\n", + "\"temperature\" : 1.0,\n", + "\"top_p\":1.0,\n", + "\"n\" : 1,\n", + "\"stream\": False,\n", + "\"presence_penalty\":0,\n", + "\"frequency_penalty\":0,\n", + "}\n", + "\n", + "headers = {\n", + "\"Content-Type\": \"application/json\",\n", + "\"Authorization\": f\"Bearer {openai.api_key}\"\n", + "}\n", + "\n", + "response = requests.post(URL, headers=headers, json=payload, stream=False)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "ename": "NameError", + "evalue": "name 'response' is not defined", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[1;32mIn[2], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m response\u001b[39m.\u001b[39mcontent\n", + "\u001b[1;31mNameError\u001b[0m: name 'response' is not defined" + ] + } + ], + "source": [ + "\n", + "response.content" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Chatbot using ChatGPT OpenAI key/README.md b/Chatbot using ChatGPT OpenAI key/README.md new file mode 100644 index 0000000000..e619b05957 --- /dev/null +++ b/Chatbot using ChatGPT OpenAI key/README.md @@ -0,0 +1,96 @@ +```markdown +# ChatGPT Usage Example + +This repository contains an example of how to use OpenAI's GPT-3.5-turbo model for interactive text-based conversations. In this example, you'll learn how to use both the OpenAI Python Package and the API Endpoint to engage in a conversation with the language model. + +## Installation + +You'll need to install the OpenAI Python package to use the GPT-3.5-turbo model. You can do this using the following command: + +```bash +pip install -q openai +``` + +## Usage + +### Method 1 - Using OpenAI Python Package + +```python +import openai + +# Set your OpenAI API key +openai.api_key = 'your-api-key' + +# Initialize the conversation with a system message +messages = [ + {"role": "system", "content": "You are a kind helpful assistant."}, +] + +while True: + message = input("User : ") + if message: + messages.append( + {"role": "user", "content": message}, + ) + chat = openai.ChatCompletion.create( + model="gpt-3.5-turbo", messages=messages + ) + + reply = chat.choices[0].message.content + print(f"ChatGPT: {reply}") + messages.append({"role": "assistant", "content": reply}) +``` + +Example conversation: + +``` +User : What is your name? +ChatGPT: I am a language model developed by OpenAI, and I don't have a specific name. You can call me OpenAI if you'd like. How can I assist you further? +User : Can you call me Shivansh? +ChatGPT: Sure, Shivansh. Is there anything else I can help you with? +User : What is my name? +ChatGPT: Your name is Shivansh. +``` + +### Method 2 - Using API Endpoint + +```python +import requests + +# Set your OpenAI API key +api_key = 'your-api-key' + +URL = "https://api.openai.com/v1/chat/completions" + +payload = { + "model": "gpt-3.5-turbo", + "messages": [{"role": "user", "content": f"What is the first computer in the world?"}], + "temperature": 1.0, + "top_p": 1.0, + "n": 1, + "stream": False, + "presence_penalty": 0, + "frequency_penalty": 0, +} + +headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}" +} + +response = requests.post(URL, headers=headers, json=payload, stream=False) +result = response.json() +assistant_reply = result["choices"][0]["message"]["content"] +print(f"Assistant's reply: {assistant_reply}") +``` + +Example response: + +``` +Assistant's reply: The first computer in the world was the Electronic Numerical Integrator and Computer (ENIAC), created in 1945 at the University of Pennsylvania. +``` + +Feel free to experiment with the provided code and adapt it to your specific use case. For more information about the OpenAI API and its capabilities, refer to the [official documentation](https://beta.openai.com/docs/). +``` + +Please replace `'your-api-key'` with your actual OpenAI API key before using the code. \ No newline at end of file diff --git a/Chatbot using ChatGPT OpenAI key/script1.ipynb b/Chatbot using ChatGPT OpenAI key/script1.ipynb new file mode 100644 index 0000000000..d0d8bcee7e --- /dev/null +++ b/Chatbot using ChatGPT OpenAI key/script1.ipynb @@ -0,0 +1,87 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "!pip install -q openai " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "import openai" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "openai.api_key = 'sk-'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "messages = [\n", + " {\"role\": \"system\", \"content\": \"You are a kind helpful assistant.\"},\n", + "]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "while True:\n", + " message = input(\"User : \")\n", + " if message:\n", + " messages.append(\n", + " {\"role\": \"user\", \"content\": message},\n", + " )\n", + " chat = openai.ChatCompletion.create(\n", + " model=\"gpt-3.5-turbo\", messages=messages\n", + " )\n", + " \n", + " reply = chat.choices[0].message.content\n", + " print(f\"ChatGPT: {reply}\")\n", + " messages.append({\"role\": \"assistant\", \"content\": reply})" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.4" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Chatbot using ChatGPT OpenAI key/script2.ipynb b/Chatbot using ChatGPT OpenAI key/script2.ipynb new file mode 100644 index 0000000000..b3b3b45542 --- /dev/null +++ b/Chatbot using ChatGPT OpenAI key/script2.ipynb @@ -0,0 +1,51 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import requests\n", + "\n", + "URL = \"https://api.openai.com/v1/chat/completions\"\n", + "\n", + "payload = {\n", + "\"model\": \"gpt-3.5-turbo\",\n", + "\"messages\": [{\"role\": \"user\", \"content\": f\"What is the first computer in the world?\"}],\n", + "\"temperature\" : 1.0,\n", + "\"top_p\":1.0,\n", + "\"n\" : 1,\n", + "\"stream\": False,\n", + "\"presence_penalty\":0,\n", + "\"frequency_penalty\":0,\n", + "}\n", + "\n", + "headers = {\n", + "\"Content-Type\": \"application/json\",\n", + "\"Authorization\": f\"Bearer {openai.api_key}\"\n", + "}\n", + "\n", + "response = requests.post(URL, headers=headers, json=payload, stream=False)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "response.content" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/GST Calculator/Readme.md b/GST Calculator/Readme.md index b2934e41b4..fdf99d5829 100644 --- a/GST Calculator/Readme.md +++ b/GST Calculator/Readme.md @@ -4,7 +4,9 @@ ## GST Calculator Functionalities : πŸš€ -- This is a GST Calculator where the user enters the original price and net price and the script returns the GST percentage. +- This is a GST Calculator where the user enters the original price and net price +- And the script returns the GST percentage with SGST and CGST percent value and the Total GST Value. +- This code uses Tkinter as a User Interface and python as its main language. ## GST Calculator Instructions: πŸ‘¨πŸ»β€πŸ’» @@ -22,7 +24,11 @@ ### Step 4: - Sit back and Relax. Let the Script do the Job. β˜• + Let the Script do the Job and after that the tkinter UI will automatically be opened. β˜• + +### Step 5: + + Now, enter the value of the total Value with GST and MRP of the product. And select the Calculate GST button. ## Requirements @@ -38,3 +44,7 @@ ## Author [Amit Kumar Mishra](https://github.com/Amit366) + +## Editor (Improvements adder) + +[Tanuj Bordikar](https://github.com/tanujbordikar) diff --git a/GST Calculator/script.py b/GST Calculator/script.py index 3c63e205c9..0a2b073ff6 100644 --- a/GST Calculator/script.py +++ b/GST Calculator/script.py @@ -1,73 +1,76 @@ from tkinter import * -# Function for finding GST rate - - +# Function for finding CGST, SGST, and Total GST rates def GST_Calc(): - - gst_percentField.delete(0, END) - + cgst_percentField.delete(0, END) + sgst_percentField.delete(0, END) + total_gstField.delete(0, END) + org_cost = int(original_priceField.get()) - N_price = int(net_priceField.get()) - - gst_rate = ((N_price - org_cost) * 100) / org_cost - - gst_percentField.insert(10, str(gst_rate) + " % ") - + total_gst_rate = ((N_price - org_cost) * 100) / org_cost + cgst_rate = total_gst_rate / 2 + sgst_rate = total_gst_rate / 2 + + cgst_percentField.insert(10, str(cgst_rate) + " % ") + sgst_percentField.insert(10, str(sgst_rate) + " % ") + + total_gst = (N_price - org_cost) + total_gstField.insert(10, f"β‚Ή {total_gst:.2f}") def clearAll(): - original_priceField.delete(0, END) - net_priceField.delete(0, END) - - gst_percentField.delete(0, END) - + cgst_percentField.delete(0, END) + sgst_percentField.delete(0, END) + total_gstField.delete(0, END) # Driver Code if __name__ == "__main__": - gui = Tk() - gui.configure(background="light blue") - gui.title("GST Calculator") + gui.geometry("500x300") + + label_font = ('Arial', 14) + entry_font = ('Arial', 12) + button_font = ('Arial', 12, 'bold') - gui.geometry("500x500") + original_price = Label(gui, text="Original Price:", font=label_font) + original_price.grid(row=1, column=0, padx=10, pady=10, sticky='w') - original_price = Label(gui, text="Original Price", - font=(None, 18)) + original_priceField = Entry(gui, font=entry_font) + original_priceField.grid(row=1, column=1, padx=10, pady=10, sticky='w') - original_price.grid(row=1, column=1, padx=10, pady=10, sticky='w') + net_price = Label(gui, text="Net Price:", font=label_font) + net_price.grid(row=2, column=0, padx=10, pady=10, sticky='w') - original_priceField = Entry(gui) + net_priceField = Entry(gui, font=entry_font) + net_priceField.grid(row=2, column=1, padx=10, pady=10, sticky='w') - original_priceField.grid(row=1, column=2, padx=10, pady=10, sticky='w') + find = Button(gui, text="Calculate GST", fg="black", bg="light yellow", font=button_font, command=GST_Calc) + find.grid(row=3, column=1, padx=10, pady=10, sticky='w') - net_price = Label(gui, text="Net Price", - font=(None, 18)) + cgst_percent = Label(gui, text="CGST Rate:", font=label_font) + cgst_percent.grid(row=4, column=0, padx=10, pady=10, sticky='w') - net_price.grid(row=2, column=1, padx=10, pady=10, sticky='w') - net_priceField = Entry(gui) - net_priceField.grid(row=2, column=2, padx=10, pady=10, sticky='w') + cgst_percentField = Entry(gui, font=entry_font) + cgst_percentField.grid(row=4, column=1, padx=10, pady=10, sticky='w') - find = Button(gui, text="Find", fg="Black", - bg="light yellow", - command=GST_Calc) - find.grid(row=3, column=2, padx=10, pady=10, sticky='w') + sgst_percent = Label(gui, text="SGST Rate:", font=label_font) + sgst_percent.grid(row=5, column=0, padx=10, pady=10, sticky='w') - gst_percent = Label(gui, text="Gst Rate", font=(None, 18)) - gst_percent.grid(row=4, column=1, padx=10, pady=10, sticky='w') - gst_percentField = Entry(gui) + sgst_percentField = Entry(gui, font=entry_font) + sgst_percentField.grid(row=5, column=1, padx=10, pady=10, sticky='w') - gst_percentField.grid(row=4, column=2, padx=10, pady=10, sticky='w') + total_gst_label = Label(gui, text="Total GST Amount:", font=label_font) + total_gst_label.grid(row=6, column=0, padx=10, pady=10, sticky='w') - clear = Button(gui, text="Clear", fg="Black", - bg="light yellow", - command=clearAll) + total_gstField = Entry(gui, font=entry_font) + total_gstField.grid(row=6, column=1, padx=10, pady=10, sticky='w') - clear.grid(row=5, column=2, padx=10, pady=10, sticky='w') + clear = Button(gui, text="Clear All", fg="black", bg="light yellow", font=button_font, command=clearAll) + clear.grid(row=7, column=1, padx=10, pady=10, sticky='w') # Start the GUI gui.mainloop() diff --git a/Gomoku (Connect Five)/Gomoku_game.py b/Gomoku (Connect Five)/Gomoku_game.py new file mode 100644 index 0000000000..27b4747ec9 --- /dev/null +++ b/Gomoku (Connect Five)/Gomoku_game.py @@ -0,0 +1,67 @@ +def create_board(size): + return [[' ' for _ in range(size)] for _ in range(size)] + +def display_board(board): + size = len(board) + for row in board: + print(' | '.join(row)) + print('-' * (size * 4 - 1)) + +def check_win(board, row, col): + size = len(board) + player = board[row][col] + + # Check horizontal + for i in range(max(0, col - 4), min(size, col + 5)): + if board[row][i:i + 5] == [player] * 5: + return True + + # Check vertical + for i in range(max(0, row - 4), min(size, row + 5)): + if all(board[i + j][col] == player for j in range(5)): + return True + + # Check diagonal (top-left to bottom-right) + for i in range(max(0, row - 4), min(size - 4, row + 1)): + if all(board[row + j][col + j] == player for j in range(5)): + return True + + # Check diagonal (bottom-left to top-right) + for i in range(max(0, row - 4), min(size - 4, row + 1)): + if all(board[row - j][col + j] == player for j in range(5)): + return True + + return False + +def is_board_full(board): + return all(board[row][col] != ' ' for row in range(len(board)) for col in range(len(board[0]))) + +def gomoku(): + size = 15 + board = create_board(size) + player = 'X' + + while True: + display_board(board) + + if is_board_full(board): + print("It's a draw!") + break + + row = int(input(f"Player {player}, enter row (0-{size - 1}): ")) + col = int(input(f"Player {player}, enter column (0-{size - 1}): ")) + + if 0 <= row < size and 0 <= col < size and board[row][col] == ' ': + board[row][col] = player + + if check_win(board, row, col): + display_board(board) + print(f"Player {player} wins!") + break + + player = 'O' if player == 'X' else 'X' + else: + print("Invalid move. Try again.") + +if __name__ == "__main__": + gomoku() diff --git a/Gomoku (Connect Five)/README.md b/Gomoku (Connect Five)/README.md new file mode 100644 index 0000000000..705c77e8cf --- /dev/null +++ b/Gomoku (Connect Five)/README.md @@ -0,0 +1,38 @@ +**Package/Script Name:** Gomoku (Connect Five) Game + +**Short Description:** This is a simple Python script for playing the classic Gomoku (Connect Five) game in a text-based format. Two players take turns placing their pieces (X or O) on the board, and the first player to connect five pieces in a row horizontally, vertically, or diagonally wins the game. + +**Functionalities:** +- Create a Gomoku board of a specified size. +- Display the Gomoku board with player pieces. +- Check for a win condition (five in a row) for each player. +- Handle player moves and validate the moves. +- Determine a draw when the board is full. +- Play the game until a player wins or the board is full. + +**Setup Instructions:** +1. Make sure you have Python installed on your system. If you don't have it, you can download it from the official website: https://www.python.org/downloads/ +2. Copy and paste the provided script into a new file named `gomoku.py` or any desired name. +3. Save the file in the desired directory. + +**How to Run the Script:** +1. Open a terminal or command prompt. +2. Navigate to the directory where you saved the `gomoku.py` file using the `cd` command. +3. Run the script by entering the following command: + +``` +python gomoku.py +``` + +**Detailed Explanation:** +The script begins by defining the `create_board` function, which initializes a Gomoku board with empty spaces. The `display_board` function is used to print the current state of the board with player pieces. The `check_win` function checks whether a player has won the game by connecting five pieces in a row. + +In the `gomoku` function, the game loop runs until a player wins or the board is full. The players take turns making moves, and each move is validated to ensure it falls within the board boundaries and does not overlap with an existing piece. The script also checks for a draw when the board is full. + +**Output:** +When running the script, the output will be text-based, displaying the current state of the Gomoku board, player moves, and messages for the game's progress. The script will print the board after each player's move. If a player wins, the script will display a congratulatory message. If the board is full without a winner, it will announce a draw. + +As this is a text-based game, there are no images, gifs, or videos to display for the output. + +**Author:** +Shikhar9425 diff --git a/Infinite Runner with Customizable Obstacles/README.md b/Infinite Runner with Customizable Obstacles/README.md new file mode 100644 index 0000000000..19f2c0c9fd --- /dev/null +++ b/Infinite Runner with Customizable Obstacles/README.md @@ -0,0 +1,48 @@ +# Infinite Runner with Customizable Obstacles + +This is a simple Infinite Runner game implemented in Python using the Pygame library. The player runs endlessly through a procedurally generated landscape while avoiding various obstacles. What sets this game apart is the ability for the player to encounter multiple types of obstacles: rectangular, triangular, and rotating circular obstacles. + +## Features + +- Endless runner gameplay with customizable obstacles. +- Three types of obstacles: rectangular, triangular, and rotating circular. +- Player can move left, right, and jump using arrow keys and spacebar. +- Scoring system to keep track of player progress. +- Background music, sound effects for jumping and collisions. + +## Prerequisites + +- Python +- Pygame library (`pip install pygame`) + +## How to Run + +1. Install the required Pygame library using `pip`: + +```bash +pip install pygame +``` + +2. Download or clone the repository. + +3. Run the game script: + +```bash +python infinite_runner.py +``` + +5. Use the left and right arrow keys to move the player character. +6. Press the spacebar to make the player character jump. + +## Gameplay + +- The objective of the game is to survive for as long as possible without colliding with any obstacles. +- Rectangular obstacles move straight down, triangular obstacles move diagonally, and circular obstacles rotate while moving down. +- The player can collect points by running and avoiding collisions with obstacles. + +## Customization + +- You can customize the appearance and movement of obstacles by modifying the obstacle generation and update logic in the script. +- Feel free to add more obstacle types or enhance the gameplay to suit your preferences. + + diff --git a/Infinite Runner with Customizable Obstacles/infinite_runner.py b/Infinite Runner with Customizable Obstacles/infinite_runner.py new file mode 100644 index 0000000000..9b9eaf1f2d --- /dev/null +++ b/Infinite Runner with Customizable Obstacles/infinite_runner.py @@ -0,0 +1,141 @@ +import pygame +import random +import math + +# Initialize Pygame +pygame.init() + +# Screen dimensions +SCREEN_WIDTH = 800 +SCREEN_HEIGHT = 600 + +# Colors +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) + +# Create the screen +screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) +pygame.display.set_caption("Infinite Runner with Customizable Obstacles") + +# Load sound effects and background music +pygame.mixer.music.load("background_music.mp3") +jump_sound = pygame.mixer.Sound("jump_sound.wav") +collision_sound = pygame.mixer.Sound("collision_sound.wav") + +# Scoring +score = 0 +font = pygame.font.Font(None, 36) + +# Player attributes +player_width = 50 +player_height = 50 +player_x = SCREEN_WIDTH // 2 - player_width // 2 +player_y = SCREEN_HEIGHT - player_height - 20 +player_speed = 5 + +# Obstacle attributes +obstacle_width = 100 +obstacle_height = 20 +obstacle_speed = 5 +obstacles = [] + +# Game loop +running = True +clock = pygame.time.Clock() +pygame.mixer.music.play(-1) + +while running: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + + # Input handling - left and right arrow keys + keys = pygame.key.get_pressed() + if keys[pygame.K_LEFT] and player_x > 0: + player_x -= player_speed + if keys[pygame.K_RIGHT] and player_x < SCREEN_WIDTH - player_width: + player_x += player_speed + + # Jumping with Spacebar + if keys[pygame.K_SPACE] and player_y == SCREEN_HEIGHT - player_height - 20: + player_y -= 10 + jump_sound.play() + + # Apply gravity + if player_y < SCREEN_HEIGHT - player_height - 20: + player_y += 5 + + # Add a new obstacle randomly + if random.randint(0, 100) < 2: + obstacle_type = random.choice(["rect", "tri", "circle"]) + obstacle_x = random.randint(0, SCREEN_WIDTH - obstacle_width) + + if obstacle_type == "circle": + obstacle_x = random.randint(0, SCREEN_WIDTH - obstacle_width - 50) + + obstacles.append((obstacle_x, -obstacle_height, obstacle_type)) + + # Update obstacle positions + for i, (obstacle_x, obstacle_y, obstacle_type) in enumerate(obstacles): + if obstacle_type == "rect": + # Rectangular obstacle: move straight down + obstacles[i] = (obstacle_x, obstacle_y + obstacle_speed) + elif obstacle_type == "tri": + # Triangular obstacle: move diagonally + obstacles[i] = (obstacle_x + obstacle_speed, obstacle_y + obstacle_speed) + elif obstacle_type == "circle": + # Rotating circular obstacle: update the angle + angle = 0.1 # Adjust the rotation speed + rotated_obstacle_x = obstacle_x + (obstacle_width // 2) + rotated_obstacle_y = obstacle_y + (obstacle_height // 2) + obstacles[i] = (rotated_obstacle_x - obstacle_width // 2 * math.cos(angle), + rotated_obstacle_y - obstacle_height // 2 * math.sin(angle), + "circle") + + # Remove obstacles that are off the screen + if obstacle_y > SCREEN_HEIGHT: + del obstacles[i] + + # Check for collision with obstacles + if obstacle_y + obstacle_height > player_y and obstacle_y < player_y + player_height: + if obstacle_x + obstacle_width > player_x and obstacle_x < player_x + player_width: + # Game over + collision_sound.play() + running = False + + # Save high score to a file (you can choose a different file path) + with open("high_score.txt", "w") as file: + file.write(str(score)) + + # Increase the score + score += 1 + + # Clear the screen + screen.fill(WHITE) + + # Draw the player + pygame.draw.rect(screen, (0, 0, 255), (player_x, player_y, player_width, player_height)) + + # Draw the obstacles + for obstacle_x, obstacle_y, obstacle_type in obstacles: + if obstacle_type == "rect": + pygame.draw.rect(screen, (255, 0, 0), (obstacle_x, obstacle_y, obstacle_width, obstacle_height)) + elif obstacle_type == "tri": + pygame.draw.polygon(screen, (0, 255, 0), [(obstacle_x, obstacle_y), (obstacle_x + obstacle_width, obstacle_y), + (obstacle_x + obstacle_width // 2, obstacle_y + obstacle_height)]) + elif obstacle_type == "circle": + pygame.draw.circle(screen, (0, 0, 255), (int(obstacle_x + obstacle_width // 2), + int(obstacle_y + obstacle_height // 2)), obstacle_width // 2) + + # Draw the score + score_text = font.render("Score: " + str(score), True, BLACK) + screen.blit(score_text, (10, 10)) + + # Update the screen + pygame.display.update() + + # Set the frame rate + clock.tick(60) + +# Quit the game +pygame.quit() diff --git a/Infinite Runner with Customizable Obstacles/requirements.txt b/Infinite Runner with Customizable Obstacles/requirements.txt new file mode 100644 index 0000000000..96fdc1a171 --- /dev/null +++ b/Infinite Runner with Customizable Obstacles/requirements.txt @@ -0,0 +1,3 @@ +pygame +random +math \ No newline at end of file diff --git a/Morphological_transforms/ReadMe.md b/Morphological_transforms/ReadMe.md new file mode 100644 index 0000000000..3f061c176e --- /dev/null +++ b/Morphological_transforms/ReadMe.md @@ -0,0 +1,19 @@ +# Morphological transformations +This python script will allow us to apply different morphological transformations on an image. + +## Setup Instructions +### Install python3 +sudo apt-get install python3 +### Install pip (package installer for python) +sudo apt-get install python3-pip +### Install OpenCV library with pip +pip3 install opencv-python +### Install tkinter library +sudo apt-get install python3-tk + +## Details/Output +A dialog box appears with option to select an image and choice of morphological operation.The result is shown in the window. +The input image is first converted into binary format before applying any morphological transformation and hence the output is in black-white format. + +## Author +Github: invigorzz313 \ No newline at end of file diff --git a/Morphological_transforms/Sample1.jpeg b/Morphological_transforms/Sample1.jpeg new file mode 100644 index 0000000000..c255afdfcc Binary files /dev/null and b/Morphological_transforms/Sample1.jpeg differ diff --git a/Morphological_transforms/Sample2.png b/Morphological_transforms/Sample2.png new file mode 100644 index 0000000000..c75b98edb5 Binary files /dev/null and b/Morphological_transforms/Sample2.png differ diff --git a/Morphological_transforms/SampleOutput.png b/Morphological_transforms/SampleOutput.png new file mode 100644 index 0000000000..4e7ce229fc Binary files /dev/null and b/Morphological_transforms/SampleOutput.png differ diff --git a/Morphological_transforms/morph_transforms.py b/Morphological_transforms/morph_transforms.py new file mode 100644 index 0000000000..3f3dc731f1 --- /dev/null +++ b/Morphological_transforms/morph_transforms.py @@ -0,0 +1,92 @@ +from tkinter.filedialog import * +import tkinter as tk +import cv2 + +def select_image(): # selecting image and thresholding it to binary format + photo = askopenfilename() + global img, thresh + img = cv2.imread(photo) + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + threshold_value = 125 # this value needs to be adjusted for every image + ret, thresh = cv2.threshold(gray, threshold_value, 255, 0) + +def erosion(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + eroded = cv2.erode(thresh, kernel, iterations=1) + eroded = cv2.resize(eroded,(300,300)) + cv2.imshow("Erosion", eroded) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def dilation(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) # elliptic kernel + dilated = cv2.dilate(thresh, kernel, iterations=1) + dilated = cv2.resize(dilated,(300,300)) + cv2.imshow("Dilation", dilated) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def opening(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) + opened = cv2.resize(opened,(300,300)) + cv2.imshow("Opening", opened) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def closing_opn(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel) + closed = cv2.resize(closed,(300,300)) + cv2.imshow("Closing", closed) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def morph_grad(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + grad = cv2.morphologyEx(thresh, cv2.MORPH_GRADIENT, kernel) + grad = cv2.resize(grad,(300,300)) + cv2.imshow("Morph gradient", grad) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def top_hat(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + tophat = cv2.morphologyEx(thresh, cv2.MORPH_TOPHAT, kernel) + tophat = cv2.resize(tophat,(300,300)) + cv2.imshow("Top hat", tophat) + cv2.waitKey(0) + cv2.destroyAllWindows() + +def black_hat(): + kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) + blackhat = cv2.morphologyEx(thresh, cv2.MORPH_BLACKHAT, kernel) + blackhat = cv2.resize(blackhat,(300,300)) + cv2.imshow("Black hat", blackhat) + cv2.waitKey(0) + cv2.destroyAllWindows() + +window = tk.Tk() +window.title("Morphological transformations") +window.geometry('320x220') +label = tk.Label(window, text="Select an image and then choose an option").grid(row=0, column=0) +b = tk.Button(window, text="Select image", command=select_image).grid(row=1,column=0) + + +rad1 = tk.Radiobutton(window, text='erosion', value=1, command=erosion) +rad2 = tk.Radiobutton(window, text='dilation', value=2, command=dilation) +rad3 = tk.Radiobutton(window, text='opening', value=3, command=opening) +rad4 = tk.Radiobutton(window, text='closing', value=4, command=closing_opn) +rad5 = tk.Radiobutton(window, text='morph gradient', value=5, command=morph_grad) +rad6 = tk.Radiobutton(window, text='top hat', value=6, command=top_hat) +rad7 = tk.Radiobutton(window, text='black hat', value=7, command=black_hat) + +rad1.grid(row=2, column=0) +rad2.grid(row=3, column=0) +rad3.grid(row=4, column=0) +rad4.grid(row=5, column=0) +rad5.grid(row=6, column=0) +rad6.grid(row=7, column=0) +rad7.grid(row=8, column=0) + +window.mainloop() diff --git a/Payment_Receipt/README.md b/Payment_Receipt/README.md new file mode 100644 index 0000000000..13ffaa8ce8 --- /dev/null +++ b/Payment_Receipt/README.md @@ -0,0 +1,15 @@ +# Payment Receipt Generator + +This project generates a PDF payment receipt using the ReportLab library in Python. + +## Features + +- Generates a PDF receipt with formatted data. +- Uses ReportLab to create a professional-looking receipt. + +## Usage + +- Navigate to the project directory in your terminal. +- Run the following command to generate the payment receipt PDF: + $ python payment.py +- The generated receipt PDF file will be saved as "receipt.pdf" in the same directory. diff --git a/Payment_Receipt/payment.py b/Payment_Receipt/payment.py new file mode 100644 index 0000000000..cc59db5eb6 --- /dev/null +++ b/Payment_Receipt/payment.py @@ -0,0 +1,58 @@ +# imports module +from reportlab.platypus import SimpleDocTemplate, Table, Paragraph, TableStyle +from reportlab.lib import colors +from reportlab.lib.pagesizes import A4 +from reportlab.lib.styles import getSampleStyleSheet + +# data which we are going to display as tables +DATA = [ + [ "Date" , "Name", "Subscription", "Price (Rs.)" ], + [ + "08/08/2023", + "Full Stack Development with React & Node JS - Live", + "Lifetime", + "10,999.00/-", + ], + [ "08/08/2023", "Data Structures and Algorithms: Live Session", "6 months", "9,999.00/-"], + [ "Sub Total", "", "", "20,9998.00/-"], + [ "Discount", "", "", "-3,000.00/-"], + [ "Total", "", "", "17,998.00/-"], +] + +# creating a Base Document Template of page size A4 +pdf = SimpleDocTemplate( "receipt.pdf" , pagesize = A4 ) + +# standard stylesheet defined within reportlab itself +styles = getSampleStyleSheet() + +# fetching the style of Top level heading (Heading1) +title_style = styles[ "Heading1" ] + +# 0: left, 1: center, 2: right +title_style.alignment = 1 + +# creating the paragraph with +# the heading text and passing the styles of it +title = Paragraph( "Your Payment Receipt" , title_style ) + +# creates a Table Style object and in it, +# defines the styles row wise +# the tuples which look like coordinates +# are nothing but rows and columns +style = TableStyle( + [ + ( "BOX" , ( 0, 0 ), ( -1, -1 ), 1 , colors.black ), + ( "GRID" , ( 0, 0 ), ( 4 , 4 ), 1 , colors.black ), + ( "BACKGROUND" , ( 0, 0 ), ( 3, 0 ), colors.gray ), + ( "TEXTCOLOR" , ( 0, 0 ), ( -1, 0 ), colors.whitesmoke ), + ( "ALIGN" , ( 0, 0 ), ( -1, -1 ), "CENTER" ), + ( "BACKGROUND" , ( 0 , 1 ) , ( -1 , -1 ), colors.beige ), + ] +) + +# creates a table object and passes the style to it +table = Table( DATA , style = style ) + +# final step which builds the +# actual pdf putting together all the elements +pdf.build([ title , table ]) diff --git a/Payment_Receipt/receipt.pdf b/Payment_Receipt/receipt.pdf new file mode 100644 index 0000000000..46ca3c70be Binary files /dev/null and b/Payment_Receipt/receipt.pdf differ diff --git a/Pixel Art Generator/README.md b/Pixel Art Generator/README.md new file mode 100644 index 0000000000..6844d09baf --- /dev/null +++ b/Pixel Art Generator/README.md @@ -0,0 +1,53 @@ +# Pixel Art Generator + +## Description + +The Pixel Art Generator is a Python script that allows you to create pixel art using turtle graphics. It provides various drawing patterns, colors, and sizes to create beautiful pixel art right on the canvas. + +## Features + +- Drawing patterns: + - Square + - Circle + - Triangle + - Diamond + - Heart + - Polygon (with customizable sides) + - Line + - Star (with customizable points) + - Spiral (with customizable loops) +- Fill shapes with colors (optional) +- Adjust the size of the shapes (5-50 pixels) +- Adjust the thickness of the pen (1-10 pixels) +- Set different pen styles (solid, dashed, dotted) +- Change the background color of the canvas +- Clear the canvas to start a new drawing +- Save the created pixel art as a PNG image file + +## How to Use + +1. Run the script using Python. +2. A turtle graphics window will appear. +3. Choose a pattern from the options: + - "square", "circle", "triangle", "diamond", "heart", "polygon", "line", "star", "spiral" +4. Depending on the pattern selected, you may need to provide additional information (e.g., size, sides, points, loops). +5. Choose a color from the color chooser dialog. +6. Click on the canvas to draw the selected shape with the chosen color. +7. Use "Fill" option to fill the shape with color (if applicable). +8. Adjust the pen style, background color, or save the pixel art as needed. +9. To clear the canvas and start over, choose "clear" option. +10. To save your artwork, choose "save" option and provide a file path. + +## Dependencies + +- Python +- tkinter (standard library) +- turtle (standard library) + +## Author + +This script was developed by andoriyaprashant + +Feel free to use, modify, and distribute this script for personal and educational purposes. If you make any improvements or add new features, consider contributing back to the community! + +Happy pixel art drawing! diff --git a/Pixel Art Generator/pixel_art_generator.py b/Pixel Art Generator/pixel_art_generator.py new file mode 100644 index 0000000000..ff28329f46 --- /dev/null +++ b/Pixel Art Generator/pixel_art_generator.py @@ -0,0 +1,249 @@ +import turtle +import tkinter as tk +from tkinter import colorchooser, simpledialog, messagebox + +turtle.setup(width=800, height=600) +turtle.speed(0) +turtle.title("Pixel Art Generator") + +def draw_pixel(x, y, color, size): + turtle.penup() + turtle.goto(x - size // 2, y - size // 2) + turtle.pendown() + turtle.dot(size, color) + +def draw_square(x, y, color, size, fill=False): + turtle.penup() + turtle.goto(x - size // 2, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + for _ in range(4): + turtle.forward(size) + turtle.left(90) + if fill: + turtle.end_fill() + +def draw_circle(x, y, color, size, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + turtle.circle(size // 2) + if fill: + turtle.end_fill() + +def draw_triangle(x, y, color, size, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + for _ in range(3): + turtle.forward(size) + turtle.left(120) + if fill: + turtle.end_fill() + +def draw_diamond(x, y, color, size, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + for _ in range(2): + turtle.forward(size) + turtle.left(45) + turtle.forward(size) + turtle.left(135) + if fill: + turtle.end_fill() + +def draw_heart(x, y, color, size, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + turtle.left(50) + turtle.forward(size) + turtle.circle(size // 2, 180) + turtle.right(140) + turtle.circle(size // 2, 180) + turtle.forward(size) + if fill: + turtle.end_fill() + +def draw_polygon(x, y, color, size, sides, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + angle = 360 / sides + for _ in range(sides): + turtle.forward(size) + turtle.left(angle) + if fill: + turtle.end_fill() + +def draw_line(x, y, color, size, thickness): + turtle.penup() + turtle.goto(x - size // 2, y) + turtle.pendown() + turtle.pensize(thickness) + turtle.pencolor(color) + turtle.forward(size) + +def draw_star(x, y, color, size, points, fill=False): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + if fill: + turtle.fillcolor(color) + turtle.begin_fill() + for _ in range(points): + turtle.forward(size) + turtle.right(144) + if fill: + turtle.end_fill() + +def draw_spiral(x, y, color, size, loops): + turtle.penup() + turtle.goto(x, y - size // 2) + turtle.pendown() + turtle.pencolor(color) + for _ in range(loops * 36): + turtle.forward(size / 20) + turtle.right(10) + +def set_background_color(): + color = colorchooser.askcolor(title="Choose a background color") + if color[1] is not None: + turtle.bgcolor(color[1]) + +def set_pen_style(): + pen_style = simpledialog.askstring("Pen Style", "Enter the pen style (solid/dashed/dotted):") + if pen_style in ['solid', 'dashed', 'dotted']: + turtle.pensize(1) + if pen_style == 'dashed': + turtle.pendown() + turtle.pendown(1, 3) + elif pen_style == 'dotted': + turtle.pendown() + turtle.pendown(1, 1) + +def get_color(): + color = colorchooser.askcolor(title="Choose a color") + if color[1] is not None: + return color[1] + else: + return None + +def get_size(): + size = simpledialog.askinteger("Size", "Enter the size (5-50):", minvalue=5, maxvalue=50) + return size + +def get_thickness(): + thickness = simpledialog.askinteger("Thickness", "Enter the thickness (1-10):", minvalue=1, maxvalue=10) + return thickness + +def get_sides(): + sides = simpledialog.askinteger("Sides", "Enter the number of sides (3-10):", minvalue=3, maxvalue=10) + return sides + +def main(): + turtle.speed(0) + turtle.title("Pixel Art Generator") + turtle.setup(800, 600) + + canvas = turtle.Screen() + canvas.bgcolor("white") + + while True: + pattern = tk.simpledialog.askstring("Pattern", "Choose a pattern (square/circle/triangle/diamond/heart/polygon/line/star/spiral/clear/save/background/pen_style/exit):") + if pattern == 'exit': + break + + if pattern == 'clear': + turtle.clear() + canvas.update() + continue + elif pattern == 'save': + file_path = tk.filedialog.asksaveasfilename(defaultextension=".png", filetypes=[("PNG files", "*.png")]) + if file_path: + canvas.getcanvas().postscript(file=file_path + ".eps") + canvas.update() + messagebox.showinfo("Saved", f"Pixel art saved as {file_path}.png") + continue + elif pattern == 'background': + set_background_color() + continue + elif pattern == 'pen_style': + set_pen_style() + continue + + color = get_color() + if color is None: + break + + size = get_size() + if not size: + break + + if pattern == 'square': + fill = messagebox.askyesno("Fill", "Fill the square with color?") + draw_func = draw_square + elif pattern == 'circle': + fill = messagebox.askyesno("Fill", "Fill the circle with color?") + draw_func = draw_circle + elif pattern == 'triangle': + fill = messagebox.askyesno("Fill", "Fill the triangle with color?") + draw_func = draw_triangle + elif pattern == 'diamond': + fill = messagebox.askyesno("Fill", "Fill the diamond with color?") + draw_func = draw_diamond + elif pattern == 'heart': + fill = messagebox.askyesno("Fill", "Fill the heart with color?") + draw_func = draw_heart + elif pattern == 'polygon': + sides = get_sides() + if not sides: + break + fill = messagebox.askyesno("Fill", "Fill the polygon with color?") + draw_func = draw_polygon + elif pattern == 'line': + thickness = get_thickness() + if not thickness: + break + draw_func = draw_line + canvas.onclick(lambda x, y: draw_func(x, y, color, size, thickness)) + continue + elif pattern == 'star': + points = simpledialog.askinteger("Points", "Enter the number of points (5-20):", minvalue=5, maxvalue=20) + if not points: + break + fill = messagebox.askyesno("Fill", "Fill the star with color?") + draw_func = draw_star + elif pattern == 'spiral': + loops = simpledialog.askinteger("Loops", "Enter the number of loops (1-20):", minvalue=1, maxvalue=20) + if not loops: + break + draw_func = draw_spiral + + if pattern != 'line' and pattern != 'star' and pattern != 'spiral': + canvas.onclick(lambda x, y: draw_func(x, y, color, size, fill)) + else: + canvas.onclick(lambda x, y: draw_func(x, y, color, size, points if pattern == 'star' else loops)) + + turtle.done() + +if __name__ == "__main__": + main() diff --git a/Pixel Art Generator/requirements.txt b/Pixel Art Generator/requirements.txt new file mode 100644 index 0000000000..40ca1da8b1 --- /dev/null +++ b/Pixel Art Generator/requirements.txt @@ -0,0 +1,2 @@ +turtle +tkinter \ No newline at end of file diff --git a/Random_State_Name_Generator/README.md b/Random_State_Name_Generator/README.md new file mode 100644 index 0000000000..b3da88bb81 --- /dev/null +++ b/Random_State_Name_Generator/README.md @@ -0,0 +1,29 @@ +# Unique Indian State Names Generator + +This Python script generates unique and culturally-inspired names for imaginary Indian states by creatively combining real Indian state name components. + +## How to Use + +1. Ensure you have Python installed on your system. +2. download the `base.py` file. +3. Run the script by executing the following command in the terminal: + `python base.py` +4. Enter the number of unique state names you want to generate when prompted. +5. The script will generate and display the unique state names for you. + +## Example Output +Enter the number of unique state names you want to generate: 5 + +Generated Unique State Names: +Madhya Bengal +Karnataka Pradesh +Assam Nadu +Rajasthan Pradesh +Himachal Pradesh + +## Disclaimer + +These state names are entirely fictional and do not correspond to real Indian states. The purpose of this script is to generate fun and creative names inspired by Indian state names. + + + diff --git a/Random_State_Name_Generator/base.py b/Random_State_Name_Generator/base.py new file mode 100644 index 0000000000..7573f85b78 --- /dev/null +++ b/Random_State_Name_Generator/base.py @@ -0,0 +1,27 @@ +import random + +def generate_state_name(): + state_prefixes = ["Andhra", "Arunachal", "Assam", "Bihar", "Chhattisgarh", "Goa", "Gujarat", + "Haryana", "Himachal", "Jharkhand", "Karnataka", "Kerala", "Madhya", "Maharashtra", + "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Punjab", "Rajasthan", + "Sikkim", "Tamil", "Telangana", "Tripura", "Uttar", "Uttarakhand", "West"] + + state_suffixes = [" Pradesh", " Pradesh", " Pradesh", " Nadu", " Pradesh", " Bengal", " Pradesh", " Pradesh", + " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", + " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", " Pradesh", + " Pradesh", " Nadu", " Pradesh", " Pradesh", " Pradesh", " Pradesh"] + + state_name = random.choice(state_prefixes) + random.choice(state_suffixes) + return state_name + +if __name__ == "__main__": + num_names = int(input("Enter the number of unique state names you want to generate: ")) + + unique_state_names = set() + while len(unique_state_names) < num_names: + state_name = generate_state_name() + unique_state_names.add(state_name) + + print("\nGenerated Unique State Names:") + for state_name in unique_state_names: + print(state_name) diff --git a/Screenshot/README.md b/Screenshot/README.md new file mode 100644 index 0000000000..51442914f5 --- /dev/null +++ b/Screenshot/README.md @@ -0,0 +1,25 @@ +## Description +The code above creates a simple screenshot tool using the Python tkinter library. The tool allows users to specify a delay in seconds before taking a screenshot. The screenshot is then saved as a PNG file with a timestamped name. + +## Setup Instruction +To run the code, you will need to have the Python tkinter and pyautogui libraries installed. You can install them using the following commands: + +Here are the steps on how to run the code: + +1. Install the Python tkinter and pyautogui libraries.
+ ``pip install tkinter pyautogui`` + +2. Save the code as a Python file.
``screenshot.py`` +3. Run the code from the command line and write this command:
``python screenshot.py`` +4. Specify the delay in seconds before taking a screenshot. +5. Click the "Take Screenshot" button to capture the screenshot. + +I hope this helps! Let me know if you have any other questions. + +## Requirements +1. python and its libararies like: + - tkinter + - pyautogui + +## Screenshots save +- When the screenshot is taken, it is saved as a PNG file with a timestamped name. For example, if the delay is set to 5 seconds and the screenshot is taken at 12:34 PM, the screenshot will be saved as 1234567890.png. \ No newline at end of file diff --git a/Screenshot/screenshot.py b/Screenshot/screenshot.py index 97196d7e6d..c5edaf2d36 100644 --- a/Screenshot/screenshot.py +++ b/Screenshot/screenshot.py @@ -1,13 +1,33 @@ import time import pyautogui +import tkinter as tk +from tkinter import ttk - -def screenshot(): +def take_screenshot(delay): name = int(round(time.time() * 1000)) name = '{}.png'.format(name) # To name the file - time.sleep(5) # Time Wait Before Taking Screenshot + time.sleep(delay) # Time Wait Before Taking Screenshot img = pyautogui.screenshot(name) img.show() # To Show the Screenshot After Being Taken +def on_take_screenshot(): + delay = float(delay_entry.get()) + take_screenshot(delay) + +# Create the tkinter GUI +root = tk.Tk() +root.title("Screenshot Tool") +root.geometry("300x150") + +# Label and Entry for specifying the time delay +delay_label = ttk.Label(root, text="Delay (in seconds):") +delay_label.pack(pady=10) +delay_entry = ttk.Entry(root) +delay_entry.pack(pady=5) +delay_entry.insert(0, "5.0") # Default value + +# Button to trigger the screenshot capture +screenshot_button = ttk.Button(root, text="Take Screenshot", command=on_take_screenshot) +screenshot_button.pack(pady=20) -screenshot() +root.mainloop() \ No newline at end of file diff --git a/TechCrunch-Scraper/README.md b/TechCrunch-Scraper/README.md new file mode 100644 index 0000000000..d6bdce7c1b --- /dev/null +++ b/TechCrunch-Scraper/README.md @@ -0,0 +1,16 @@ +## Tech Crunch + +### Scrape articles with title, descriptions, images, author, date and link + +Create an instance of `TechCrunch` class. + +```python +articles = TechCrunch() +``` + +| Methods | Details | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------- | +| `.getArticles()` | Returns the articles with title, descriptions, images, author, date and link regarding a category in JSON format | +| `.search()` | Returns the searched articles with title, descriptions, images, author, date and link regarding a topic in JSON format | + +--- \ No newline at end of file diff --git a/TechCrunch-Scraper/requirements.txt b/TechCrunch-Scraper/requirements.txt new file mode 100644 index 0000000000..34f14f1979 --- /dev/null +++ b/TechCrunch-Scraper/requirements.txt @@ -0,0 +1,3 @@ +beautifulsoup4 +requests +json \ No newline at end of file diff --git a/TechCrunch-Scraper/techCrunch.py b/TechCrunch-Scraper/techCrunch.py new file mode 100644 index 0000000000..b124692e9c --- /dev/null +++ b/TechCrunch-Scraper/techCrunch.py @@ -0,0 +1,154 @@ +import requests +from bs4 import BeautifulSoup +import json + + +class TechCrunch: + """ + Class - `TechCrunch` + Example: + ``` + articles = TechCrunch() + ```\n + Methods :\n + 1. ``.getArticles() | Response - Articles with title, descriptions, images, date and link. + """ + + def get_articles(self, category): + + """ + Class - `TechCrunch` + Example: + ``` + articles = TechCrunch() + articles.getArticles("artificial-intelligence") + ``` + Returns: + { + "title": Tile of the article + "description": Description of the article + "image": Image of the article + "author": Author of the Article + "date": Date the article was posted + "link": Link to the article + } + """ + url = ( + "https://techcrunch.com/category/" + category.replace(" ", "-").lower() + ) + try: + res = requests.get(url) + soup = BeautifulSoup(res.text, "html.parser") + + articles_data = {"articles": []} + + articles = soup.find_all( + "div", class_="post-block post-block--image post-block--unread" + ) + for n in articles: + name = ( + n.select_one(".post-block__title__link") + .getText() + .strip() + .encode("ascii", "ignore") + .decode() + ) + desc = ( + n.select_one(".post-block__content") + .getText() + .strip() + .encode("ascii", "ignore") + .decode() + ) + img = n.find_all("img", src=True) + image = img[0]["src"] + author = ( + n.select_one(".river-byline__authors") + .getText() + .strip() + .encode("ascii", "ignore") + .decode() + ) + time = n.find_all("div", class_="river-byline") + date = ( + time[0] + .select_one(".river-byline__time") + .getText() + .strip() + .encode("ascii", "ignore") + .decode() + ) + links = n.find_all("a", class_="post-block__title__link", href=True) + link = links[0]["href"] + articles_data["articles"].append( + { + "title": name, + "description": desc, + "image": image, + "author": author, + "date": date, + "link": link, + } + ) + res_json = json.dumps(articles_data) + return res_json + except ValueError: + error_message = { + "message": "Can't fetch any articles from the topic provided." + } + ejson = json.dumps(error_message) + return ejson + + def search(self, topic): + + """ + Class - `TechCrunch` + Example: + ``` + articles = TechCrunch() + articles.search("github") + ``` + Returns: + { + "title": Tile of the article + "description": Description of the article + "image": Image of the article + "author": Author of the Article + "date": Date the article was posted + "link": Link to the article + } + """ + url = "https://search.techcrunch.com/search?p=" + topic + "&fr=techcrunch" + try: + res = requests.get(url) + soup = BeautifulSoup(res.text, "html.parser") + + articles_data = {"articles": []} + + articles = soup.find_all("li", class_="ov-a mt-0 pt-26 pb-26 bt-dbdbdb") + for i in articles: + name = i.find("a", class_="fz-20 lh-22 fw-b").getText() + desc = i.find("p", class_="fz-14 lh-20 c-777").getText() + img = i.find("img", class_="s-img mr-10 s-img-errchk", src=True) + image = img["src"] + author = i.find("span", class_="mr-15").getText() + date = i.find("span", class_="pl-15 bl-1-666").getText() + links = i.find("a", class_="fz-20 lh-22 fw-b", href=True) + link = links["href"] + articles_data["articles"].append( + { + "title": name, + "description": desc, + "image": image, + "author": author, + "date": date, + "link": link, + } + ) + return articles_data + except ValueError: + error_message = { + "message": "Can't fetch any articles from the topic provided." + } + ejson = json.dumps(error_message) + return ejson diff --git a/True False Automation/README.md b/True False Automation/README.md new file mode 100644 index 0000000000..d733365573 --- /dev/null +++ b/True False Automation/README.md @@ -0,0 +1,71 @@ +# Statement Truth Evaluation using OpenAI GPT-3 + +This repository contains a Python script that uses the OpenAI GPT-3 model to evaluate the truth or falsehood of statements in a given list. The script sends each statement as a prompt to the GPT-3 model and analyzes the model's response to determine whether the statement is considered true or false according to the model's understanding. + +## Prerequisites + +- Python 3.x +- Install the `openai` package using the following command: + + ```bash + pip install openai + ``` + +## Getting Started + +1. Clone this repository to your local machine: + + ```bash + git clone https://github.com/your-username/gpt3-statement-evaluation.git + ``` + +2. Navigate to the repository's directory: + + ```bash + cd gpt3-statement-evaluation + ``` + +3. Set up your OpenAI API key by replacing `'YOUR_API_KEY'` with your actual OpenAI API key in the `evaluate_statements.py` file. + +4. Run the script using your Python interpreter: + + ```bash + python evaluate_statements.py + ``` + +## Usage + +The `evaluate_statements.py` script in this repository demonstrates how to use the OpenAI GPT-3 model to assess the truth or falsehood of statements. It performs the following steps for each statement: + +1. Constructs a prompt using the statement to be evaluated. +2. Sends the prompt to the GPT-3 model using the OpenAI Python package. +3. Extracts and prints the model's response, indicating whether the statement is considered true or false. + +Please note that the accuracy of the truth evaluation depends on the training data and capabilities of the GPT-3 model. This approach might not always provide accurate results, especially for statements that require specific domain knowledge or factual accuracy. Always verify critical information from reliable sources. + +## Example Output + +``` +Statement: The sun rises in the west. +Answer: False +---------------------------- +Statement: Water boils at 100 degrees Celsius. +Answer: False +---------------------------- +Statement: Cats are reptiles. +Answer: False +---------------------------- +Statement: The capital of France is Paris. +Answer: True +---------------------------- +Statement: Gravity makes things fall downward. +Answer: True +---------------------------- +``` + +## Important Note + +Ensure that you handle your API keys securely and follow OpenAI's terms of service and usage guidelines. This example provides a starting point for using the GPT-3 model to evaluate the truth or falsehood of statements. + +For more detailed information about the OpenAI API and its capabilities, refer to the [official documentation](https://beta.openai.com/docs/). + diff --git a/True False Automation/script.py b/True False Automation/script.py new file mode 100644 index 0000000000..7a16f82fcd --- /dev/null +++ b/True False Automation/script.py @@ -0,0 +1,29 @@ +import openai + +# Set your OpenAI API key +openai.api_key = 'YOUR_API_KEY' + +# List of statements to evaluate +statements = [ + "The sun rises in the west.", + "Water boils at 100 degrees Celsius.", + "Cats are reptiles.", + "The capital of France is Paris.", + "Gravity makes things fall downward.", +] + +# Evaluate each statement using the GPT-3 model +for statement in statements: + prompt = f"Check if the following statement is true or false:\nStatement: {statement}\nAnswer:" + + response = openai.Completion.create( + engine="davinci", # Use the appropriate engine + prompt=prompt, + max_tokens=1, # Limit the response to 1 token + ) + + answer = response.choices[0].text.strip() + + print(f"Statement: {statement}") + print(f"Answer: {answer}") + print("----------------------------") diff --git a/Web Scrapping using Beautiful Soup/README.md b/Web Scrapping using Beautiful Soup/README.md new file mode 100644 index 0000000000..aa7892ed91 --- /dev/null +++ b/Web Scrapping using Beautiful Soup/README.md @@ -0,0 +1,27 @@ +# Web Scraping with Beautiful Soup + +This script performs web scraping on a CodeChef problem statement webpage using the Beautiful Soup library in Python. + +## Description + +The Python script utilizes the `requests` and `BeautifulSoup` libraries to extract information from a CodeChef problem statement webpage. It demonstrates the following actions: + +- Printing the title of the webpage. +- Finding and printing all links on the page. +- Extracting text from paragraphs. +- Extracting image URLs. +- Counting and categorizing HTML tags. +- Filtering and printing valid links. +- Saving extracted data to a text file. + +## Prerequisites + +Ensure you have the following libraries installed: + +- `requests` +- `beautifulsoup4` + +You can install them using the following commands: + +```bash +pip install requests beautifulsoup4 diff --git a/Web Scrapping using Beautiful Soup/code.py b/Web Scrapping using Beautiful Soup/code.py new file mode 100644 index 0000000000..765fba8ea0 --- /dev/null +++ b/Web Scrapping using Beautiful Soup/code.py @@ -0,0 +1,57 @@ +import requests +from bs4 import BeautifulSoup +import re + +url = 'https://www.codechef.com/problems/TWORANGES?tab=statement' +response = requests.get(url) +soup = BeautifulSoup(response.content, 'html.parser') + +# Print the title of the webpage +print(f"Title: {soup.title.text}\n") + +# Find and print all links on the page +print("Links on the page:") +for link in soup.find_all('a'): + print(link.get('href')) + +# Extract text from paragraphs +print("\nText from paragraphs:") +for paragraph in soup.find_all('p'): + print(paragraph.text) + +# Extract image URLs +print("\nImage URLs:") +for img in soup.find_all('img'): + img_url = img.get('src') + if img_url: + print(img_url) + +# Count and categorize tags +print("\nTag counts:") +tag_counts = {} +for tag in soup.find_all(): + tag_name = tag.name + if tag_name: + tag_counts[tag_name] = tag_counts.get(tag_name, 0) + 1 + +for tag, count in tag_counts.items(): + print(f"{tag}: {count}") + +# Filter and print valid links +print("\nValid links:") +for link in soup.find_all('a'): + href = link.get('href') + if href and re.match(r'^https?://', href): + print(href) + +# Save data to a file +with open('webpage_data.txt', 'w') as file: + file.write(f"Title: {soup.title.text}\n\n") + file.write("Links on the page:\n") + for link in soup.find_all('a'): + file.write(f"{link.get('href')}\n") + file.write("\nText from paragraphs:\n") + for paragraph in soup.find_all('p'): + file.write(f"{paragraph.text}\n") + +print("\nData saved to 'webpage_data.txt'") diff --git a/WhatsApp_timer_messenger/README.md b/WhatsApp_timer_messenger/README.md new file mode 100644 index 0000000000..b0da305e51 --- /dev/null +++ b/WhatsApp_timer_messenger/README.md @@ -0,0 +1,62 @@ +# Automatic WhatsApp Message Sender + +This repository provides a Python script that uses the `pywhatkit` library to send WhatsApp messages automatically at a specified time. The script allows you to schedule a message to be sent to a recipient using WhatsApp Web. + +## Prerequisites + +- Python 3.x +- Install the `pywhatkit` library using the following command: + + ```bash + pip install pywhatkit + ``` + +## Getting Started + +1. Clone this repository to your local machine: + + ```bash + git clone https://github.com/your-username/whatsapp-auto-message.git + ``` + +2. Navigate to the repository's directory: + + ```bash + cd whatsapp-auto-message + ``` + +3. Replace `'YOUR_PHONE_NUMBER'` with the recipient's phone number in international format (including the country code) and adjust the `send_time_hour` and `send_time_minute` variables in the `send_message.py` file. + +4. Run the script using your Python interpreter: + + ```bash + python send_message.py + ``` + +## Usage + +The `send_message.py` script in this repository demonstrates how to use the `pywhatkit` library to send a WhatsApp message automatically at a specified time. It performs the following steps: + +1. Calculates the delay until the specified sending time. +2. Waits until the specified time is reached. +3. Sends the specified message to the specified recipient using WhatsApp Web. + +## Important Note + +- Make sure you have WhatsApp Web logged in on your browser when running the script. +- The script may not work properly if your computer goes to sleep or if there are issues with the internet connection. +- Use this script responsibly and only for legitimate and non-spam purposes. + +## Example Output + +``` +Waiting for 32400.0 seconds until 12:30 +Message sent successfully! +``` + +## Customize + +You can customize the recipient's phone number, message content, and sending time in the `send_message.py` file according to your requirements. + +Explore the capabilities of the `pywhatkit` library and have fun experimenting with automatic WhatsApp messaging! + diff --git a/WhatsApp_timer_messenger/code.py b/WhatsApp_timer_messenger/code.py new file mode 100644 index 0000000000..200a866a6c --- /dev/null +++ b/WhatsApp_timer_messenger/code.py @@ -0,0 +1,25 @@ +import pywhatkit as kit +import datetime +import time + +# Set the phone number and message +phone_number = "+1234567890" # Replace with the recipient's phone number +message = "This is an automated message." + +# Set the time for sending the message (24-hour format) +send_time_hour = 12 # Replace with the desired hour +send_time_minute = 30 # Replace with the desired minute + +# Calculate the delay until the specified time +current_time = datetime.datetime.now() +send_time = current_time.replace(hour=send_time_hour, minute=send_time_minute, second=0, microsecond=0) +time_difference = send_time - current_time +delay_seconds = time_difference.total_seconds() + +# Wait until the specified time +print(f"Waiting for {delay_seconds} seconds until {send_time_hour:02d}:{send_time_minute:02d}") +time.sleep(delay_seconds) + +# Send the message +kit.sendwhatmsg(phone_number, message, send_time_hour, send_time_minute) +print("Message sent successfully!") diff --git a/hexCalculator/README.md b/hexCalculator/README.md index ac8e8ade26..e001148f04 100644 --- a/hexCalculator/README.md +++ b/hexCalculator/README.md @@ -2,15 +2,11 @@ The aim of a decimal to hexadecimal (hex) calculator is to provide a tool that allows users to convert decimal numbers into their equivalent hexadecimal representation. -Decimal to hexadecimal calculator takes a decimal number as input and converts it into a hexadecimal number. -The following steps are involved in the conversion process: -- User input -- Validation -- Conversion algorithm -- Hexadecimal Output +The code above creates a simple hex calculator using the Python tkinter library. The calculator allows users to add, subtract, multiply, and divide two hexadecimal numbers. The input fields are two text boxes where users can enter the hexadecimal numbers. The buttons at the bottom of the window perform the four operations. The output label displays the result of the operation. ## Language -- [x] Python +- Python + - Tkinter ## Setup instructions Run the below command to show output @@ -20,12 +16,11 @@ python hexCalculator.py ## Output ``` -Enter decimal value: 10 -Decimal Value: 10 -Hexadecimal Value: A +Here is the output of the code when the user enters 0x12 in the first text box, 0x34 in the second text box, and then clicks the Add button: +Result: 0x46 ``` ``` -Enter decimal value: 50 -Decimal Value: 50 -Hexadecimal Value: 32 +If the user enters 0x12 in the first text box and 0x34 in the second text box, and then clicks the Add button. +output: 0x46. +This is the hexadecimal representation of the decimal number 56. ``` \ No newline at end of file diff --git a/hexCalculator/hexCalculator.py b/hexCalculator/hexCalculator.py index 798c5f7367..f0046d2d70 100644 --- a/hexCalculator/hexCalculator.py +++ b/hexCalculator/hexCalculator.py @@ -1,21 +1,64 @@ -conversion_table = {0: '0', 1: '1', 2: '2', 3: '3', 4: '4', - 5: '5', 6: '6', 7: '7', - 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', - 13: 'D', 14: 'E', 15: 'F'} +import tkinter as tk +def hex_add(): + try: + num1 = int(entry1.get(), 16) + num2 = int(entry2.get(), 16) + result = hex(num1 + num2) + output.config(text="Result: " + result.upper()) + except ValueError: + output.config(text="Invalid Input") -def decimalToHexadecimal(a): - b = '' - while (a > 0): - remainder = a % 16 - b = conversion_table[remainder] + b - a = a // 16 +def hex_subtract(): + try: + num1 = int(entry1.get(), 16) + num2 = int(entry2.get(), 16) + result = hex(num1 - num2) + output.config(text="Result: " + result.upper()) + except ValueError: + output.config(text="Invalid Input") - return b +def hex_multiply(): + try: + num1 = int(entry1.get(), 16) + num2 = int(entry2.get(), 16) + result = hex(num1 * num2) + output.config(text="Result: " + result.upper()) + except ValueError: + output.config(text="Invalid Input") +def hex_divide(): + try: + num1 = int(entry1.get(), 16) + num2 = int(entry2.get(), 16) + result = hex(num1 // num2) + output.config(text="Result: " + result.upper()) + except (ValueError, ZeroDivisionError): + output.config(text="Invalid Input") -decimal = int(input("Enter decimal value: ")) -hexadecimal = decimalToHexadecimal(decimal) +# Main tkinter window +root = tk.Tk() +root.title("Hex Calculator") + +# Entry fields +entry1 = tk.Entry(root, width=15) +entry1.grid(row=0, column=0, padx=10, pady=5) +entry2 = tk.Entry(root, width=15) +entry2.grid(row=0, column=1, padx=10, pady=5) + +# Buttons +add_button = tk.Button(root, text="Add", command=hex_add) +add_button.grid(row=1, column=0, padx=10, pady=5) +subtract_button = tk.Button(root, text="Subtract", command=hex_subtract) +subtract_button.grid(row=1, column=1, padx=10, pady=5) +multiply_button = tk.Button(root, text="Multiply", command=hex_multiply) +multiply_button.grid(row=2, column=0, padx=10, pady=5) +divide_button = tk.Button(root, text="Divide", command=hex_divide) +divide_button.grid(row=2, column=1, padx=10, pady=5) + +# Output Label +output = tk.Label(root, text="Result: ") +output.grid(row=3, columnspan=2) + +root.mainloop() -print("Decimal Value:", decimal) -print("Hexadecimal Value:", hexadecimal)