Calculate time dilation with python

In this example imagine two object one is Earth And another object is traveling in the space

\[ t_0 = t \sqrt{1 – \frac{v^2}{c^2}} \]
  • t0: Represents the dilated time experienced by the object which is traveling or seems traveling from earth
  • t: Time passed on earth
  • v: Velocity of the traveling object.
  • c: Speed of light in the vacuum.

Now back to our example. Here user will enter the time passed on earth and the speed of the traveling object. The program will calculate the time dilation.


from math import sqrt
c=299792458 #speed of light in m/s

t=eval(input("Enter the time passed on earth in year: "))
v=c
while not v<c:
	v=eval(input("Enter the speed of the object in m/s: "))
	if v>c:
		print("Speed of the object must be less than the speed of light:",c)
def time_dilation(c,v,t):
	t_0=t*sqrt(1-(v**2/c**2))
	return t_0
time_passed_to_object=time_dilation(c,v,t)
print("time passed to the object",time_passed_to_object," year")
print("time difference",t-time_passed_to_object," year")


For example if time pass on earth 20 years and the object is traveling in speed 7497924 m/s

The program will print this result based on user input

Enter the time passed on earth in year: 20
Enter the speed of the object in m/s: 7497924
time passed to the object 19.993743829255635  year
time difference 0.006256170744364908  year

How to convert text to sentence with python and nltk

We can easily convert text to sentence in python with nltk by tokenize sentence..

First install nltk

pip install nltk

Download nltk data .

NLTK requires data files for tokenization. run the code in a python program to download the data.


import nltk
nltk.download('punkt')


After download the necessary data


from nltk import tokenize

text="In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us. Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace."

sentence_list=tokenize.sent_tokenize(text)
print(sentence_list)


#for sentence in sentence_list:
#	print(sentence)

for i, sentence in enumerate(sentence_list, start=1):
    print(f"Sentence {i}: {sentence}")


this will print the the result like this

['In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us.', 'Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace.']
Sentence 1: In the symphony of existence, we discover our interconnectedness and the boundless spiritual power within us.
Sentence 2: Together, we build a world where empathy thrives, sparking hope and lighting the way to a future filled with harmony and peace.

How to get all possible combinations with python

Python is rich with wonderful standard library so you do not have to write everything from the very beginning. With permutations from iterators we can get wonderful and useful result with less code

>In this example code we get the user input as string

> Get the user input length

> Then run a for loop based on the user input str length

> get the combinations with permutation with store the combination in a list

Like this

Enter your word or sentence or number: 123
['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']



from itertools import permutations
user_input=str(input("Enter your word or sentence or number: "))
l=len(user_input)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(user_input,i))
	for element in a:
		x=(''.join(element))
		combinations.append(x)
print(combinations)


We can make this more wonderful to print out with pprint. Also print out all combinations from a list.


from itertools import permutations
from pprint import pprint
# flower names
flower_names = ["rose","orchid", "sunflower"]

l=len(flower_names)+1
combinations=[]
for i in range(1,l):
	a=list(permutations(flower_names,i))
	combinations.append(a)
pprint(combinations)


You will get this result on running this code

[[('rose',), ('orchid',), ('sunflower',)],
 [('rose', 'orchid'),
  ('rose', 'sunflower'),
  ('orchid', 'rose'),
  ('orchid', 'sunflower'),
  ('sunflower', 'rose'),
  ('sunflower', 'orchid')],
 [('rose', 'orchid', 'sunflower'),
  ('rose', 'sunflower', 'orchid'),
  ('orchid', 'rose', 'sunflower'),
  ('orchid', 'sunflower', 'rose'),
  ('sunflower', 'rose', 'orchid'),
  ('sunflower', 'orchid', 'rose')]]

Easy Temperature Conversions with Python: A Beginner’s Guide (Celsius, Fahrenheit, Kelvin)

Basic Temperature Conversion Program

This program takes a temperature input from the user, identifies the scale (Celsius, Fahrenheit, Kelvin), and converts it to the other two scales. Let’s break down the code step-by-step.

For higher accuracy in the Kelvin scale use 273.15 instead of 273


x = str(input("Enter in which scale you measured temperature (Celsius, Fahrenheit, Kelvin)? Enter C or F or K: "))
# 160 is 5*32  .... equations are simplified
if x=="C" or x=="c":
    c=eval(input("Enter your temperature in Celsius scale: "))
    to_fahrenheit=(9*c+160)/5
    to_kelvin=c+273
    print("Celsius :", c,  "\nFahrenheit :", to_fahrenheit,  "\nKelvin: ", to_kelvin)
    
elif x=="F" or x=="f":
    f=eval(input("Enter your temperature in Fahrenheit scale: "))
    to_celsius=(5*f-160)/9
    to_kelvin=((5*f-160)/9)+273
    print("Celsius :", to_celsius,  "\nFahrenheit :", f,  "\nKelvin: ", to_kelvin)
    

elif x== "K" or x=="k":
    k=eval(input("Enter your temperature in Kalvin scale: "))
    to_celsius=k-273
    to_fahrenheit=(9*(k-273)+160)/5
    print("Celsius :", to_celsius,  "\nFahrenheit :", to_fahrenheit,  "\nKelvin: ", k)



Explanation

>Firstly the this code takes input from user in which scale user measured the temperature

>Then user asked for another input in which scale they want to convert

  • The user is prompted to enter the temperature scale: ‘C’ for Celsius, ‘F’ for Fahrenheit, or ‘K’ for Kelvin.
  • Conversion Calculations:
  • Depending on the input scale, the program calculates the temperature in the other two scales using the following formulas:

Celsius to Fahrenheit:

\[ F = \frac{9}{5}C + 32 \]

Celsius to Kelvin:

\[ K = C + 273 \]

Fahrenheit to Celsius:

\[ C = \frac{5}{9}(F – 32) \]

Fahrenheit to Kelvin:

\[ K = \frac{5}{9}(F – 32) + 273 \]

Kelvin to Celsius:

\[ C = K – 273 \]

Kelvin to Fahrenheit:

\[ F = \frac{9}{5}(K – 273) + 32 \]

Complete code with some added feature


x = str(input("Enter in which scale you measured temperature (Celsius, Fahrenheit, Kelvin)? Enter C or F or K: "))
# 160 is 5*32  .... equations are simplified
if x == "C" or x == "c":
    c = eval(input("Enter your temperature in Celsius scale: "))
    to_fahrenheit = (9 * c + 160) / 5
    to_kelvin = c + 273
    while to_kelvin < 0:
        print("Temperature cannot be less than absolute zero")
        c = eval(input("Enter your temperature in Celsius scale: "))
        to_fahrenheit = (9 * c + 160) / 5
        to_kelvin = c + 273
    print("Celsius:", c, "\nFahrenheit:", to_fahrenheit, "\nKelvin:", to_kelvin)
    
elif x == "F" or x == "f":
    f = eval(input("Enter your temperature in Fahrenheit scale: "))
    to_celsius = (5 * f - 160) / 9
    to_kelvin = ((5 * f - 160) / 9) + 273
    while to_kelvin < 0:
        print("Temperature cannot be less than absolute zero")
        f = eval(input("Enter your temperature in Fahrenheit scale: "))
        to_celsius = (5 * f - 160) / 9
        to_kelvin = ((5 * f - 160) / 9) + 273
    print("Celsius:", to_celsius, "\nFahrenheit:", f, "\nKelvin:", to_kelvin)
    
elif x == "K" or x == "k":
    k = eval(input("Enter your temperature in Kelvin scale: "))
    while k < 0:
        print("Temperature cannot be less than absolute zero")
        k = eval(input("Enter your temperature in Kelvin scale: "))
    to_celsius = k - 273
    to_fahrenheit = (9 * (k - 273) + 160) / 5
    print("Celsius:", to_celsius, "\nFahrenheit:", to_fahrenheit, "\nKelvin:", k)




Create your first chat application with Flask and Socketio

We will use socketio for real-time messaging

First install our dependency for this application


pip install flask
pip install flask-socketio


How it will work.

Every user will get an unique key.

If the the other user submit the other users key that will send the message. its like sending message to unique username

Generate Unique Key for every user


import string
import random
def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))
generated_key=generate_key()
print(generated_key)


Its a 4 digit key for testing purpose. In real application must use long key with other randomness to make sure two key will not be same. Instead of key we can use unique user name. Thas another topic . For simplicity we will use this 4 digit key. Uptate it later on your necessary.

Our application structure….

stept by step Explanation

when the user load the page on borwer they will go to this page

@app.route('/')
def index():
    return render_template('index.html')

After loading the page they will connect with the socketio they will get an uniuqe key

and this key will send to the user by emiting the key to the client

also save the key in the python dictionary with the socketio sid to handle users connection activity later

When the user connected with socketio

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

When the user disconnected from socketio

If the user diconnected we will remove the user from the python dictionary.( its like active user management)

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

When the user will send menssage to specific user.( the logic handles on serverside socketio)

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)


The Complete Server Side code


from flask import Flask, render_template,request
from flask_socketio import SocketIO, emit
import random
import string

app = Flask(__name__)
socketio = SocketIO(app)
active_connections = {} 


def generate_key():
    key_length = 4
    characters = string.digits
    return ''.join(random.choice(characters) for _ in range(key_length))

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('connect')
def on_connect():
    print('User connected')
    key = generate_key()
    active_connections[key] = request.sid
    emit('key_assigned', {'key': key})

@socketio.on('disconnect')
def on_disconnect():
    print('User disconnected')
    for key, sid in active_connections.items():
        if sid == request.sid:
            del active_connections[key]
            break

@socketio.on('send_message')
def send_message(data):
    key = data['key']
    message = data['message']
    if key in active_connections:
        recipient_sid = active_connections[key]
        emit('receive_message', {'message': message}, to=recipient_sid)
    else:
        emit('receive_message', {'message': 'Does not Match'}, to=request.sid)

if __name__ == '__main__':
    socketio.run(app, debug=True)


the client side code( the code we will send to browser when load the landing page index.html)

Step by step guide
First add the scoketuio client side library

<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Application Prototype</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    
</head>
<body>

    <script>

    </script>
</body>
</html>

Add html content to show the message and users key

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <h1>Python Scoketio Chat Prototype</h1>

<!--User unique key will be shows here -->
    <p>Your Unique Key: <span id="uniqueKey"></span></p>

<!--This is where user will enter the friends key to send message to friend -->
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>


<!-- This is where the send and received message will shown
    <div id="chat"></div>


<!-- This is where user will write the message
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>


    </script>
</body>
</html>

The logical part javascript

connect to socket io

const socket = io();

       const socket = io();
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
        });

When key sent by server this code will extract the key from data and place it to the html with the id name ‘uniquekey’

Initiate Chat

        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

this function will get key which user enter to start chat and send it to the another if that user is active

when the pervious user send the message other user will get it from client side with this code

       socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });

This will recieve the message from server and set it to the html chat div .

Start continuouis chat

if the user initiate chat . user can send countinous chat as long as the receiver is active

as friend key already stored when the initiate the chat. so user do not have to add the key every time when send message

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

The complete code javascript code for client side


    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>

The complete client side code (index.html)


<!DOCTYPE html>
<html>
<head>
    <title>Private Chat Prototype With Socketio and Flask</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
</head>
<body>
    <h1>Private Chat Prototype With socketio and flask</h1>
    <p>Your Unique Key: <span id="uniqueKey"></span></p>
    <input type="text" id="friendKey" placeholder="Enter Friend's Key"><br>
    <button onclick="startChat()">Start Chat</button><br>
    <div id="chat"></div>
    <div>
        <input type="text" id="messageInput" placeholder="Enter your message">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>
        const socket = io();

        // Store the friend's key for sending messages
        let friendKey = '';

        // Listen for the 'key_assigned' event to display the assigned key
        socket.on('key_assigned', (data) => {
            const uniqueKeySpan = document.getElementById('uniqueKey');
            uniqueKeySpan.textContent = data.key;
            console.log(data.key);
        });


        function startChat() {
            friendKey = document.getElementById('friendKey').value;
            const message = "Hello, let's chat!";
            socket.emit('send_message', { key: friendKey, message: message });
        }

        function sendMessage() {
            const message = document.getElementById('messageInput').value;
            if (friendKey && message) {
                socket.emit('send_message', { key: friendKey, message: message });
                const chatDiv = document.getElementById('chat');
                const messageDiv = document.createElement('div');
                messageDiv.textContent = `You: ${message}`;
                chatDiv.appendChild(messageDiv);
            }
        }

        socket.on('receive_message', (data) => {
            const chatDiv = document.getElementById('chat');
            const messageDiv = document.createElement('div');
            messageDiv.textContent = `Friend: ${data.message}`;
            chatDiv.appendChild(messageDiv);
        });


    </script>
</body>
</html>



Structure

├── app.py
└── templates
    └── index.html

How you will test. it?

First run the code. and open the localhost link http://127.0.0.1:5000/ in the browser. Another one in in new incognito mode

So it will act like two unique user for your testing. Then Enter the other users unique key ( which works like unique username here) Then send message . Thats all. customize the code your necessary. Happy coding!

You can also get this project code from github
https://github.com/01one/flask-socketio-chat-application

Difference between statement and keyword in programming

Statement

A single, complete instruction in a programming language that tells the computer to perform a specific action.
Examples: assigning values, making decisions, controlling loops, displaying output.

Keyword

A word reserved by the programming language that has a predefined meaning and purpose.
Examples: words like if, else, for, while, int, class that control logic and define data types.

StatementKeyword
Serve as fundamental units of executable code.Reserved words within the programming language itself.
Instruct the computer to perform specific actions.Carry special meanings and functionalities.
Conditional Statements: if (condition) {…}Conditional Keywords: if, else, for, while