python – Classroom issues

Hello Goodnight I am new to the world of programming and I am studying the classes and functions part and I am trying to create a class called 'Square & # 39; where I would ask people two values ​​and compare the values ​​across two questions and tell the person if the multiplication this value would generate a square or not, but I do not bear fruit because I miss things that I do not know what that they are.

Square class ():

def __init__(self, perguntaum, perguntadois):
    self.lista1 = ()
    self.lista2 = ()
    self.perguntaum = perguntaum
    self.perguntadois = perguntadois

def perguntas(self):
    perguntaum = int(input('Digite o primeiro número, em metros: '))
    perguntadois = int(input('Agora digite o segundo número: '))
    self.lista1.append(perguntaum)
    self.lista2.append(perguntadois)
    return perguntaum and perguntadois

def verificarquadrado(self):
    if self.lista1 == self.lista2:
        print('Esse é um quadrado!')
    while self.lista1 != self.lista2:
        print('Tente novamente, esse não é um quadrado!')
        return self.perguntas

If anyone can help me, I like it a lot, and first of all thank you very much!

How to navigate in a list with Threading in Python?

I have a question, I was watching the threading module,

but I do not understand how to browse a list in more than one thread at a time,

Maybe it's a simple question and I appreciate your help

Greetings

python – How to create a proxy with scapy

I would like to create a proxy using scapy to show how proxies are used in the real world. What I'm trying to accomplish here is that the client sends these packets so that I can examine the data sent and that the proxy is at the center of the transfer along those packets.

I've read online here to create a script to send http requests, but I'd like to send all the data, not just the http requests.
https://www.endpoint.com/blog/2015/04/29/raw-packet-manipulation-with-scapy

import logging 
logging.getLogger("scapy").setLevel(1)  

from scapy.all import *  

def make_test(x,y):     
    request = "GET / HTTP/1.1rnHost: " + y  + "rn"     
    p = IP(dst=x)/TCP()/request     
    out = sr1(p)     
    if out:         
        out.show() 
    if __name__ == "__main__":
    interact(mydict=globals(), mybanner="Scapy HTTP Tester")

Also, I've seen here how to transfer traffic
Scapy Shipping Packages

#!/usr/bin/python

import sys
import time
from scapy.all import sniff, sendp, ARP, Ether

if len(sys.argv) < 3:
    print sys.argv(0) + "  "
    sys.exit(0)

iface = "wlan1"
target_ip = sys.argv(1)
fake_ip = sys.argv(2)

ethernet = Ether()
arp = ARP(pdst=target_ip, psrc=fake_ip, op="is-at")
packet = ethernet / arp

while True:
    sendp(packet, iface=iface)
    time.sleep(10)

Are there any online guides or scripts already describing how to send and forward packages using scapy?

python – Displays the information entered by the user on a song

This program takes the information entered by the user on a song and adds it to a dictionary before printing the raw dictionary. This program works fine the first time but it fails a second time and displays a TypeError error.

song_info = song_info (artist, song, published)
TypeError: The object & # 39; dict & # 39; is not callable

def song_info(artist_name, song_title, release_date = None):        # We give no value to 'release_date'. 'None' is a placeholder
    """Build a dictionary containing information about an album."""
    song_dict = {'artist': artist_name, 'song': song_title} # We add the two arguments provided to the dictionary
    if release_date:                                         # If there is an argument provided for 'release_date' then execute this block.
        song_dict('released') = release_date                # Add the release date to the dictionary.
    return song_dict



# Prepare the prompts.
song_prompt = "Which song are you thinking of? "
artist_prompt = "Who's the artist? "
released_prompt = "When was it released? "

while True:
    released = None                                          # We give the 'release' no value so if the user does not provide input for this variable python wont cause 
                                                             # any problems
    print("nEnter 'quit' at any time to stop.")

    song = input(song_prompt)
    if song == 'quit':
        break
    artist = input(artist_prompt)
    if artist == 'quit':
        break

    release_question = input("Do you know when it was released?(yes/no) ")  # Ask the use if they know the release date.
    if release_question == 'yes':                                           # If they know execute this block.
        released = input(released_prompt)                               # Ask the user for the release date.

        if released == 'quit':    
            break

    elif release_question == 'quit':
        break


    song_info = song_info(artist, song, released)
    print(song_info)

python – A queue of persistent file system operations using sqlite and JSON text fields

I want to implement a persistent queue for file system operations (copy, delete, move) that must be secure for processes and threads. The module will be used by a daemon (called qcpwho can accept Tasks of several customers. It must also be possible to process multiple items in parallel queue.

I'm a python novice and I'm looking for general advice (even punk) on python best practices and object-oriented programming in general. I am particularly happy if my implementation of Task.from_json() as @staticmethod is appropriate. I was not sure because it conditionally instantiates subclasses of Task rather than a plain Task.

tâches.py

from pathlib import Path
from typing import Union, Optional
import shutil
import os
import json
import sqlite3    
import logging

Pathish = Union(Path, str)


class Task:
    """Abstract class for qcp Tasks. Should not be instantiated directly."""

    def __init__(self) -> None:
        self.type = 0

    def run(self) -> None:
        """Run the Task"""
        pass

    @staticmethod
    def from_dict(x, validate: bool = False) -> "Task":
        """Create a Task of the appropriate subclass from a python dict"""
        task_type = x("type")

        if task_type == -1:
            return KillTask()
        elif task_type == 0:
            return Task()
        elif task_type == 1:
            return EchoTask(x("msg"))
        elif task_type == 2:
            return FileTask(x("src"), validate=validate)
        elif task_type == 3:
            return DeleteTask(x("src"), validate=validate)
        elif task_type == 4:
            return CopyTask(x("src"), x("dst"), validate=validate)
        elif task_type == 5:
            return MoveTask(x("src"), x("dst"), validate=validate)
        elif task_type == 6:
            raise NotImplementedError
        else:
            raise ValueError

    def __repr__(self) -> str:
        return 'NULL'

    def __eq__(self, other) -> bool:
        return self.__dict__ == other.__dict__

    def __ne__(self, other) -> bool:
        return self.__dict__ != other.__dict__


class KillTask(Task):
    """Kill the qcp server"""
    def __init__(self) -> None:
        self.type = -1
        super().__init__()

    def run(self) -> None:
        raise NotImplementedError

    def __repr__(self) -> str:
        return 'KILL'


class EchoTask(Task):
    """Log a message"""
    def __init__(self,  msg: str) -> None:
        super().__init__()
        self.msg = msg
        self.type = 1

    def run(self) -> None:
        print(self.msg)

    def __repr__(self) -> str:
        return f'Echo: "{self.msg}"'


class FileTask(Task):
    """Abstract class for all file-based tasks"""
    def __init__(self, src: Pathish, validate: bool = True) -> None:
        super().__init__()
        self.validate = validate
        self.src = Path(src).as_posix()
        self.type = 2
        if validate:
            self.__validate__()

    def __validate__(self) -> None:
        if not Path(self.src).exists():
            raise FileNotFoundError(f'{self.src} does not exist')
        elif not (Path(self.src).is_dir() or Path(self.src).is_file()):
            raise TypeError(f'{self.src} is neither a file nor directory')


class DeleteTask(FileTask):
    """Delete a file"""
    def __init__(self, src: Pathish, validate: bool = True) -> None:
        super().__init__(src=src, validate=validate)
        self.type = 3

    def run(self) -> None:
        os.unlink(self.src)

    def __repr__(self) -> str:
        return f'DEL {self.src}'


class CopyTask(FileTask):
    """Copy a file"""
    def __init__(self, src: Pathish, dst: Pathish, validate: bool = True) -> None:
        super().__init__(src=src, validate=False)
        self.dst = Path(dst).as_posix()
        self.type = 4
        self.validate = validate
        if validate:
            self.__validate__()

    def __repr__(self) -> str:
        return f'COPY {self.src} -> {self.dst}'

    def __validate__(self) -> None:
        super().__validate__()
        if Path(self.dst).exists():
            raise FileExistsError

    def run(self) -> None:
        self.__validate__()
        shutil.copy(self.src, self.dst)


class MoveTask(CopyTask):
    """Move a file"""
    def __init__(self, src: Pathish, dst: Pathish, validate: bool = True) -> None:
        super().__init__(src=src, dst=dst, validate=validate)
        self.type = 5

    def run(self) -> None:
        super().__validate__()
        shutil.move(self.src, self.dst)

    def __repr__(self) -> str:
        return f'MOVE {self.src} -> {self.dst}'


class TaskQueueElement:
    """An enqueued Task"""

    task = None  #: A Task
    status = None  #: Status of the queued Task
    priority = None  #: Priority of the queued Task

    def __init__(self, task: Task, priority: 1) -> None:
        self.task = task
        self.priority = priority

    def __lt__(self, other) -> bool:
        return self.priority < other.priority

    def __gt__(self, other) -> bool:
        return self.priority > other.priority

    def __eq__(self, other) -> bool:
        return self.__dict__ == other.__dict__

    def __ne__(self, other) -> bool:
        return self.__dict__ != other.__dict__


class TaskQueue:
    """A prioritzed queue for tasks"""
    def __init__(self, path: Pathish = 'qcp.db') -> None:
        """
        Instantiate a TaskQueue

        :param path: Path to store the persistent queue
        :type path: Path or str
        """

        self.con = sqlite3.connect(path, isolation_level="EXCLUSIVE")
        self.path = Path(path)

        cur = self.con.cursor()
        cur.execute("""
           CREATE TABLE IF NOT EXISTS tasks (
              priority INTEGER,
              task TEXT,
              status INTEGER,
              owner INTEGER              
            )              
        """)
        self.con.commit()

    @property
    def n_total(self) -> int:
        """Count of all tasks in queue (including failed and completed)"""
        cur = self.con.cursor()
        return cur.execute("SELECT COUNT(1) from tasks").fetchall()(0)(0)

    @property
    def n_pending(self) -> int:
        """Number of pending tasks"""
        cur = self.con.cursor()
        return cur.execute("SELECT COUNT(1) FROM tasks WHERE status = 0").fetchall()(0)(0)

    @property
    def n_running(self) -> int:
        """Count of currently running tasks"""
        cur = self.con.cursor()
        return cur.execute("SELECT COUNT(1) FROM tasks WHERE status = 1").fetchall()(0)(0)

    @property
    def n_done(self) -> int:
        """count of completed tasks"""
        cur = self.con.cursor()
        return cur.execute("SELECT COUNT(1) from tasks WHERE status = 2").fetchall()(0)(0)

    @property
    def n_failed(self) -> int:
        """count of completed tasks"""
        cur = self.con.cursor()
        return cur.execute("SELECT COUNT(1) from tasks WHERE status = -1").fetchall()(0)(0)

    def put(self, task: "Task", priority: Optional(int) = None) -> None:
        """
        Enqueue a task

        :param task: Task to be added to the queue
        :type task: Task
        :param priority: (optional) priority for executing `task` (tasks with lower priority will be executed earlier)
        :type priority: int
        """

        cur = self.con.cursor()
        cur.execute(
            "INSERT INTO tasks (priority, task, status) VALUES (?, ?, ?)", (priority, json.dumps(task.__dict__), 0)
        )
        self.con.commit()

    def pop(self) -> "Task":
        """
        Retrieves Task object and sets status of Task in database to "in progress" (1)

        :raises AlreadyUnderEvaluationError: If trying to pop a tasks that is already being processed  (i.e. if a race
        condition occurs if the queue is processed in parallel)
        """
        cur = self.con.cursor()
        cur.execute("SELECT _ROWID_ from tasks WHERE status = 0 ORDER BY priority LIMIT 1")
        oid = cur.fetchall()(0)(0).__str__()
        self.mark_running(oid, id(self))

        cur.execute("SELECT owner, task FROM tasks WHERE _ROWID_ = ?", oid)
        record = cur.fetchall()(0)
        if record(0) != id(self):
            raise AlreadyUnderEvaluationError

        task = Task.from_dict(json.loads(record(1)))
        task.oid = oid
        return task

    def peek(self) -> "Task":
        """
        Retrieves Task object without changing its status in the queue
        """
        cur = self.con.cursor()
        cur.execute("SELECT * from tasks ORDER BY priority LIMIT 1")
        record = cur.fetchall()(0)
        oid = record(0).__str__()
        task = Task.from_dict(json.loads(record(1)), validate=False)
        task.oid = oid
        return task

    def print(self, n: int = 10) -> None:
        """
        Print an overview of the queue

        :param n: number of tasks to preview
        :type n: int
        """
        assert isinstance(n, int) and n > 0
        cur = self.con.cursor()
        cur.execute("SELECT status, task from tasks ORDER BY priority LIMIT ?", (str(n), ))
        records = cur.fetchall()
        for record in records:
            print(f"({record(0)}) {Task.from_dict(json.loads(record(1)))}")

    def mark_pending(self, oid: int) -> None:
        """
        Mark the operation with the _ROWID_ `oid` as "pending" (0)

        :param oid: ID of the task to mark
        :type oid: int
        """
        cur = self.con.cursor()
        cur.execute("UPDATE tasks SET status = 0, owner = NULL where _ROWID_ = ?", (oid, ))
        self.con.commit()

    def mark_running(self, oid: int, owner: int) -> None:
        """Mark the operation with the _ROWID_ `oid` as "running" (1). The "owner" Id is to ensure no two processes
        are trying to execute the same operation

        :param oid: ID of the task to mark
        :type oid: int
        :param owner: Id of the process that is handling the operation
        :type owner: int
        """
        cur = self.con.cursor()
        cur.execute("UPDATE tasks SET status = 1, owner = ? where _ROWID_ = ?", (owner, oid))
        self.con.commit()

    def mark_done(self, oid: int) -> None:
        """
        Mark the operation with the _ROWID_ `oid` as "done" (2)
        :param oid: ID of the task to mark
        :type oid: int
        """
        cur = self.con.cursor()
        cur.execute("UPDATE tasks SET status = 2, owner = NULL where _ROWID_ = ?", (oid, ))
        self.con.commit()

    def mark_failed(self, oid: int) -> None:
        """
        Mark the operation with the _ROWID_ `oid` as "failed" (-1)

        :param oid: ID of the task to mark
        :type oid: int
        """
        cur = self.con.cursor()
        cur.execute("UPDATE tasks SET status = -1, owner = NULL where _ROWID_ = ?", (oid, ))
        self.con.commit()

    def run(self) -> None:
        """Execute all pending tasks"""
        if self.n_pending < 1:
            logging.getLogger().warn("Queue is empty")

        while self.n_pending > 0:
            op = self.pop()
            op.run()
            self.mark_done(op.oid)


class AlreadyUnderEvaluationError(Exception):
    """This Task is already being processed by a different worker"""
    pass

A quick demo in pytest:

import tasks
import pytest

def test_TaskQueue(tmp_path):
    """TaskQueue can queue and execute tasks"""
    src = tmp_path.joinpath("foo")
    src.touch()

    q = tasks.TaskQueue(tmp_path.joinpath("qcp.db"))
    q.put(tasks.CopyTask(src, tmp_path.joinpath("copied_file")))
    q.run()
    assert tmp_path.joinpath("copied_file").is_file()
    q.put(tasks.MoveTask(tmp_path.joinpath("copied_file"), tmp_path.joinpath("moved_file")))
    q.run()
    assert not tmp_path.joinpath("copied_file").is_file()
    assert tmp_path.joinpath("moved_file").is_file()
    q.put(tasks.DeleteTask(tmp_path.joinpath("moved_file")))
    q.run()
    assert not tmp_path.joinpath("moved_file").is_file()
    assert src.is_file()

p .: I am aware that I do not care logging for a single log call, but I plan to include more logging in the future

Interactive folder file organizer (alphanumeric and type) for macOS / Linux in Python

A simple interactive Python script to organize messy folders on the computer, supports macOS and linux but not windows. The mini-program has the following features:

  • Create alphanumeric folders (A-Z / 0-9) based on the available set of letters in the folder specified in the path and move the folders / files to the newly created folders.
  • Creation of folders specific to the type (Audio, Video …) and moving files in the appropriate type folders.
  • Run directly from shell or from a Python interpreter.
  • Interactive.

It is planned to add more features to the code and to possibly perform other optimizations / updates, here is my implementation in Python, I hope it suits you, suggestions for improvements / features to add / problems encountered when using the code are more than welcome. The program works fine, no bug has been found so far, however, you may want to test it before using it on a folder containing test files to get you used to it.

#!/usr/bin/env python
import os
import string
import shutil
import random


def thank_user():
    """Print a thank you message and end program."""
    print(5 * ' ' + 10 * '=')
    print('Thank you for using file organizer.')
    print(5 * ' ' + 10 * '=')
    exit()


def get_folder_contents(path):
    """Return folder contents."""
    while not os.path.exists(path):
        path = input('Invalid path, please enter a valid path or q to exit: ').rstrip()
        if path == 'q':
            thank_user()
    os.chdir(path)
    return (file for file in os.listdir(path) if file != '.DS_Store')


def welcome_user():
    """Print a welcome message."""
    print(5 * ' ' + 10 * '=')
    print('Welcome to file organizer.')
    print(5 * ' ' + 10 * '=')
    action = input('Do you wish to continue? y/n: ')
    while action != 'y' and action != 'n':
        print(f'Invalid command {action}')
        action = input('Do you wish to continue? y/n: ')
    if action == 'n':
        thank_user()
    if action == 'y':
        pass


def create_alpha_num_folders(path):
    """Create alpha-numeric folders for first characters present in files of the given path ."""
    folder_contents = get_folder_contents(path)
    if not folder_contents:
        print(f"0 files found in {str(path).split('/')(-1)}")
        print(105 * '=')
        thank_user()
    chars_to_produce = set((item(0).upper() for item in folder_contents))
    invalid_folders = (folder for folder in folder_contents if folder in string.ascii_uppercase
                       or folder in string.digits)
    if invalid_folders:
        print(f'Found the following {len(invalid_folders)} folders named from A - Z/ 1 - n:')
        for invalid_folder in invalid_folders:
            print(invalid_folder)
        while invalid_folders:
            action = input(f'Enter q to exit. Do you want to to rename the {len(invalid_folders)}'
                           f' invalid folder(s)? y/n/q: ')
            if action == 'q' or action == 'n':
                print('Creating A - Z / 1 - n folders unsuccessful.')
                thank_user()
            if action == 'y':
                confirm = input(f'Are you sure, do you want to rename {len(invalid_folders)} invalid folders? y/n: ')
                while not confirm == 'y' or confirm == 'n':
                    print(f'Invalid command {confirm}')
                    confirm = input(f'Are you sure, do you want to rename {len(invalid_folders)} '
                                    f'invalid folders? y/n: ')
                if confirm == 'y':
                    count = random.randint(10 ** 6, 10 ** 7)
                    for filename in invalid_folders:
                        new_name = filename + '_' + str(count)
                        os.rename(filename, new_name)
                    print(f'Changed {len(invalid_folders)} folder name(s) successful.')
                    break
                if confirm == 'n':
                    thank_user()
            else:
                print(f'Invalid command {action}')
    for char in sorted(chars_to_produce):
        os.mkdir(char)
        print(f'Creation of folder {char} successful.')
    print(105 * '=')


def get_supported_formats():
    """Return supported formats."""
    formats = {
        'AUDIO': ('aif', 'cda', 'mid', 'midi', 'mp3', 'mpa', 'ogg', 'wav', 'wma', 'wpl'),
        'COMPRESSED': ('7z', 'arj', 'deb', 'pkg', 'rar', 'rpm', 'tar.gz', 'z', 'zip'),
        'DISC': ('bin', 'dmg', 'iso', 'toast', 'vcd'),
        'DATA': ('csv', 'dat', 'db', 'dbf', 'log', 'mdb', 'sav', 'sql', 'tar', 'xml'),
        'EXECUTABLE': ('apk', 'bat', 'bin', 'cgi', 'pl', 'com', 'exe', 'gadget', 'jar', 'wsf'),
        'FONT': ('fnt', 'fon', 'otf', 'ttf'),
        'IMAGE': ('ai', 'bmp', 'gif', 'ico', 'jpeg', 'jpg', 'png', 'ps', 'psd', 'svg', 'tif', 'tiff'),
        'INTERNET': ('asp', 'aspx', 'cer', 'cfm', 'css', 'htm', 'html', 'js', 'jsp',
                     'part', 'php', 'rss', 'xhtml'),
        'PRESENTATION': ('key', 'odp', 'pps', 'ppt', 'pptx'),
        'PROGRAMMING': ('c', 'class', 'cpp', 'cs', 'h', 'java', 'sh', 'swift', 'vb', 'py'),
        'SPREADSHEET': ('ods', 'xlr', 'xls', 'xlsx'),
        'SYSTEM': ('bak', 'cab', 'cfg', 'cpl', 'cur', 'dll', 'dmp', 'drv', 'icns', 'ini',
                   'lnk', 'msi', 'sys', 'tmp'),
        'VIDEO': ('3g2', '3gp', 'avi', 'flv', 'h264', 'm4v', 'mkv', 'mov', 'mp4', 'mpg', 'mpeg',
                  'rm', 'swf', 'vob', 'wmv', 'webm'),
        'WORD_PROCESSOR': ('doc', 'docx', 'odt', 'pdf', 'rtf', 'tex', 'txt', 'wks', 'wps', 'wpd'),
        'SUBTITLES': ('srt', 'sub', 'sbv')
    }
    return formats


def get_extension_type(extension):
    """Return extension type ex: mp3 --> AUDIO."""
    formats = get_supported_formats()
    possible_extensions = tuple(ext for ext, exts in formats.items() if extension.lower() in exts)
    if not possible_extensions:
        return ('UNCLASSIFIED',)
    return possible_extensions


def get_file_extension(filename):
    """Return file extension"""
    return filename.split('.')(-1).lower()


def get_folder_extensions(path):
    """Return all folder extensions."""
    folder_contents = get_folder_contents(path)
    return set((get_file_extension(filename) for filename in folder_contents))


def create_folders(path):
    """Create alpha-numeric folders or type specific folders in the given path."""
    folder_contents = get_folder_contents(path)
    print(f"Current folder: {str(path).split('/')(-1)}")
    print(f'Folder contents ({len(folder_contents)}) items:')
    print(105 * '=')
    if not folder_contents:
        print(f"0 files found in {str(path).split('/')(-1)}")
        print(105 * '=')
        thank_user()
    for number, filename in enumerate(sorted(folder_contents), 1):
        if os.path.isdir(filename):
            print(f'{number}. Folder: {filename}')
        if os.path.isfile(filename):
            print(f'{number}. File: {filename}')
    print(105 * '=')
    action1 = input(f'Enter q to exit. Do you want to group the {len(folder_contents)}'
                    f' items above Alpha-numerically (A-Z / 0-9) or by type? a/t/q: ')
    while action1 != 'a' and action1 != 't' and action1 != 'q':
        print(f'Invalid command {action1}')
        action1 = input(f'Enter q to exit. Do you want to group the {len(folder_contents)}'
                        f' items above Alpha-numerically (A-Z / 0-9) or by type? a/t/q: ')
    if action1 == 'a':
        action2 = input(f"Enter q to exit. Are you sure, do you want to create Alpha-numeric (A-Z / 0-9) folders in "
                        f"{str(path).split('/')(-1)}? y/n/q: ")
        while action2 != 'y' and action2 != 'n' and action2 != 'q':
            print(f'Invalid command {action2}')
            action2 = input(
                f"Enter q to exit. Are you sure, do you want to create Alpha-numeric (A-Z / 0-9) folders in "
                f"{str(path).split('/')(-1)}? y/n/q: ")
        if action2 == 'n' or action2 == 'q':
            print('Creation of new Alpha-numeric (A-Z / 0-9) folders unsuccessful.')
            thank_user()
        if action2 == 'y':
            create_alpha_num_folders(path)
            return 'alpha'
    if action1 == 't':
        folder_extensions = get_folder_extensions(path)
        new_folders = set((get_extension_type(extension) for extension in folder_extensions))
        new_folder_names = (folder_name for folder_names in new_folders for folder_name in folder_names)
        print('New type folders to create: ')
        for number, name in enumerate(sorted(new_folder_names), 1):
            print(number, name)
        action2 = input(f"Enter q to exit. Are you sure do you want to create the {len(new_folder_names)} folders"
                        f" above in {str(path).split('/')(-1)}? y/n/q: ")
        while action2 != 'y' and action2 != 'n' and action2 != 'q':
            print(f'Invalid command {action2}')
            action2 = input(f"Enter q to exit. Are you sure do you want to create the {len(new_folder_names)} folders"
                            f" above in {str(path).split('/')(-1)}? y/n/q: ")
        if action2 == 'y':
            for folder in sorted(new_folder_names):
                try:
                    os.mkdir(folder)
                    print(f'Creation of {folder} folder successful.')
                except FileExistsError:
                    print(f'Filename {folder} already exists.')
                    print(f'Creation of {folder} folder unsuccessful.')
            return 'type'
        if action2 == 'n' or action2 == 'q':
            print(f'Creation of {len(new_folder_names)} folders unsuccessful.')
            thank_user()
    if action1 == 'q':
        print('Creation of new folders unsuccessful.')
        thank_user()


def organize_files(path):
    """Move files and folders into new organized relevant folders."""
    folder_types = create_folders(path)
    if folder_types == 'alpha':
        new_folder_contents = get_folder_contents(path)
        files_to_move = (folder for folder in new_folder_contents if folder not in string.ascii_uppercase
                         and folder not in string.digits)
        new_alpha_folders = (folder for folder in new_folder_contents if folder in string.ascii_uppercase
                             or folder in string.digits)
        print(f"Current folder: {str(path).split('/')(-1)}")
        print(f'Folder contents to be moved ({len(files_to_move)}) items:')
        print(105 * '=')
        for number, filename in enumerate(sorted(files_to_move), 1):
            if os.path.isdir(filename):
                print(f'{number}. Folder: {filename}')
            if os.path.isfile(filename):
                print(f'{number}. File: {filename}')
        print(105 * '=')
        action = input(f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above'
                       f' to Alpha-numeric (A-Z / 0-9) folders? y/n/q: ')
        while action != 'q' and action != 'y' and action != 'n':
            print(f'Invalid command {action}')
            action = input(
                f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above'
                f' to Alpha-numeric (A-Z / 0-9) folders? y/n/q: ')
        if action == 'q' or action == 'n':
            print(f'Organization of {len(files_to_move)} Alpha-numerically (A-Z / 0-9) unsuccessful.')
            thank_user()
        if action == 'y':
            for filename in files_to_move:
                for folder_name in new_alpha_folders:
                    if filename.startswith(folder_name.lower()) or filename.startswith(folder_name):
                        shutil.move(filename, folder_name)
                        print(f'Moving successful ... {filename} to {folder_name}')
    if folder_types == 'type':
        new_folder_contents = get_folder_contents(path)
        files_to_move = (folder for folder in new_folder_contents if folder not in get_supported_formats())
        new_type_folders = (folder for folder in new_folder_contents if folder in get_supported_formats())
        print(f"Current folder: {str(path).split('/')(-1)}")
        print(f'Folder contents to be moved ({len(files_to_move)}) items:')
        print(105 * '=')
        for number, filename in enumerate(sorted(files_to_move, key=get_file_extension), 1):
            if os.path.isdir(filename):
                print(f'{number}. Folder: {filename}')
            if os.path.isfile(filename):
                print(f'{number}. File: {filename}')
        print(105 * '=')
        action = input(f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above'
                       f' into type specific folders? y/n/q: ')
        while action != 'y' and action != 'n' and action != 'q':
            print(f'Invalid command {action}')
            action = input(
                f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above'
                f' into type specific folders? y/n/q: ')
        if action == 'n' or action == 'q':
            print(f'Organization of {len(files_to_move)} by type unsuccessful.')
            thank_user()
        if action == 'y':
            for filename in files_to_move:
                file_type = get_extension_type(get_file_extension(filename))
                for folder_name in new_type_folders:
                    if file_type(0) == folder_name:
                        shutil.move(filename, folder_name)
                        print(f'Moving successful ... {filename} to {folder_name}')
    thank_user()


if __name__ == '__main__':
    welcome_user()
    path_to_folder = input('Please enter a valid path or q to exit: ').rstrip()
    if path_to_folder == 'q':
        thank_user()
    organize_files(path_to_folder)

novice – Resolution of the Kruskal algorithm with the help of Python

That's the problem of Uva online judge. Visit https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=975

In an episode of the show Dick Van Dyke, little Richie connects the
freckles on his father's back to form an image of the bell of freedom.
Alas, one of the freckles turns out to be a scar. His Ripley's
the commitment falls through. Consider Dick's return as a plane with
freckles at various (x, y) Locations. Your job is to tell Richie how
connect the dots to minimize the amount of ink used. Richie
connects the points by drawing straight lines between pairs, possibly
lift the pen between the lines. When Richie has finished, there must be a
sequence of connected lines from one freckle to another freckle.

Contribution

The entry starts with a single positive integer on a single line
indicating the number of following cases, each of them being
described below. This line is followed by a white line and there is
also an empty line between two consecutive entries. The first line
contains 0 < n ≤ 100, the number of freckles on Dick's back. For each
freckle, a line follows; each next line contains two real numbers
indicating the (x, y) coordinates of the freckle.

Exit

For each test case, the output must follow the description below. the
the outputs of two consecutive cases will be separated by a blank line.
Your program prints a single real number with two decimal places: the
total minimum length of ink lines that can connect all freckles.

I passed it, but when I see the code, it seems really messy. I am probably a beginner in algorithm and python. I want to keep the format of having Edge and Freckle class for some reasons.

can you give me some tips to make it more functional or improve performance?

Thank you in advance.

import math
import sys

class Freckle:

    def __init__(self, freckle_id, x_position, y_position):
        self.freckle_id = freckle_id
        self.x_position = x_position
        self.y_position = y_position


class Edge(object):

    def __init__(self, edge_id,  start_freckle, to_freckle, weight):
        self.edge_id = edge_id
        self.start_freckle = start_freckle
        self.to_freckle = to_freckle
        self.weight = weight
        self.spanning_tree = False





def assign_weight(freckle_list, edge_list):

    # for one in range(0, len(freckle_list)-1, 1):
    #     for two in range(one+1, len(freckle_list)):
    #         weight = euclidean_distance(freckle_list(one), freckle_list(two))
    #         edge = Edge(freckle_list(two), euclidean_distance(freckle_list(one), freckle_list(two)))
    #         freckle_list(one).edge_list.append(edge)
    edge_id = 0
    for one in range(0, len(freckle_list)-1):
        for two in range(1, len(freckle_list), 1):
            weight = euclidean_distance(freckle_list(one), freckle_list(two))
            if weight == 0:
                continue
            else:
                edge = Edge(edge_id, freckle_list(one), freckle_list(two), weight)
                edge_list.append(edge)
            edge_id +=1


def euclidean_distance(edge_one, edge_two):
    distance = math.sqrt((edge_one.x_position-edge_two.x_position)**2 +(edge_one.y_position-edge_two.y_position)**2)
    return distance


def kruskal(answer_list, freckle_list, freckle_num):
    edge_list = list()
    assign_weight(freckle_list, edge_list)
    union_find = UnionFind(len(edge_list))
    mst_tree = list()
    edge_list.sort(key=lambda one_edge: one_edge.weight)
    for edge in edge_list:
        if not edge.spanning_tree:
            if union_find.find_set(edge.start_freckle.freckle_id) != union_find.find_set(edge.to_freckle.freckle_id):
                mst_tree.append(edge)
                if len(mst_tree) == freckle_num - 1:
                    edge.spanning_tree = True
                union_find.merge_set(edge.start_freckle.freckle_id, edge.to_freckle.freckle_id)
            edge_list.sort(key=lambda one_edge: one_edge.weight)
        else:
            return
    total = 0
    for x in mst_tree:
        total += x.weight

    answer_list.append(round(total, 2))



class UnionFind:

    def __init__(self, freckle_num):
        self.parent = None
        self.create_set(freckle_num)

    def create_set(self, freckle_num):
        self.parent = list(range(freckle_num))
    ## parent(0) = 0, parent(1)=1 ...

    def find_set(self, freckle_num):
        if self.parent(freckle_num) != freckle_num:
            self.parent(freckle_num) = self.find_set(self.parent(freckle_num))
        return self.parent(freckle_num)

    ##who is the parent of freckle number 3? , then it should return which is the root

    def merge_set(self, one_freckle, two_freckle):
        self.parent(self.find_set(one_freckle)) = self.find_set(two_freckle)

    ##merge it. For example... parent(0) = 0, 1

def main():
    answer_list = list()

    freckle_list = list()
    case_num = sys.stdin.readline()
    case_num = int(case_num)

    for num in range(0, case_num):
        freckle_list = list()
        skip_blank = sys.stdin.readline()
        freckle_num = int(sys.stdin.readline())
        for one_freckle in range(0, freckle_num):
            positions = sys.stdin.readline()
            positions = positions.rstrip('n')
            positions = positions.split(" ")
            x_position = float(positions(0))
            y_position = float(positions(1))
            freckle = Freckle(one_freckle, x_position, y_position)
            freckle_list.append(freckle)
        # if num == 0:
        #     sys.stdout.write("n")
        kruskal(answer_list, freckle_list, freckle_num)
    count = 0
    for answer in answer_list:
        #sys.stdout.write(str(answer))
        print(answer)
        if count < len(answer_list)-1:
            print()
        count +=1


if __name__ == "__main__":
    main()

contribution

3

5
1.0 1.0
3.0 1.0
1.0 3.0
5.0 4.0
7.0 7.0

4
1.0 1.0
-1.0 1.0
-1.0 -1.0
1.0 -1.0

6
3.0 3.0
5.0 -2.0
8.0 4.0
12.5 -3.0
-5.0 -1.0
0.0 0.0

expected production


11.21

6.00

27.39
```

how to make the operating system using python

Chinese smartphone maker Xiaomi recently spoke of the success of Redmi Note 7. The company said that 50 lakh units of the Redmi Note 7 series had been sold to date. This series includes Redmi Note 7, Redmi Note 7 Pro and Redmi Note 7s. However, Redmi Note 7 has been abandoned in India. https://4phone.in/xiaomi-redmi-note-8-pro-confirmed/

javascript – Use JS as Frontend and Python for Backend

I'm studying JavaScript and, as part of the study, I have to train, for example to create a website, but I think it's a bad idea. use JS in the backend. so I remembered the dear Python who is perfect for that. However, I do not know how or if it is possible to connect a JS interface to a Python server without doing everything in Flask / Django, or everything in NodeJS and JS. Is there a way to make this connection?

Optimized encrypted currency wallet using a language such as python

Create your own portfolio of cryptographic assets and explain your reasoning.
Premium. Measure the correlation of your portfolio assets and examine their liquidity