import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import pandas as pd
import numpy as np
import threading
import os

def create_tooltip(widget, text):
    def enter(event):
        tooltip = tk.Toplevel(widget)
        tooltip.wm_overrideredirect(True)
        x, y, _, _ = widget.bbox("insert")
        x += widget.winfo_rootx() + 25
        y += widget.winfo_rooty() + 25
        tooltip.wm_geometry(f"+{x}+{y}")
        label = ttk.Label(
            tooltip, text=text, background="white", borderwidth=1, relief="solid"
        )
        label.pack()

    def leave(event):
        for t in widget.winfo_children():
            t.destroy()

    widget.bind("<Enter>", enter)
    widget.bind("<Leave>", leave)

def compare_files(file1, file2, output_file, id_cols, file_format="csv"):
    # Add a function to read different file formats
    def read_file(file, format):
        if format == "csv":
            return pd.read_csv(file)
        elif format == "excel":
            return pd.read_excel(file)
        else:
            raise ValueError("Unsupported file format.")

    # Read the files using the appropriate function
    df1 = read_file(file1, file_format)
    df2 = read_file(file2, file_format)

    # Set multi-level index
    df1["seq"] = df1.groupby(id_cols).cumcount()
    df2["seq"] = df2.groupby(id_cols).cumcount()
    df1 = df1.set_index(id_cols + ["seq"])
    df2 = df2.set_index(id_cols + ["seq"])

    # Merge DataFrames on index
    df1["row_number_file1"] = np.arange(2, len(df1) + 2)
    df2["row_number_file2"] = np.arange(2, len(df2) + 2)
    merged_df = df1.merge(
        df2,
        how="outer",
        left_index=True,
        right_index=True,
        suffixes=("_file1", "_file2"),
        indicator=True,
    )

    merged_df["row_number_file2"] = merged_df["row_number_file2"].fillna(0).astype(int)

    # Replace left_only and right_only in _merge column with actual file names
    merged_df["_merge"] = merged_df["_merge"].replace(
        {"left_only": file1 + "_ONLY", "right_only": file2 + "_ONLY"}
    )

    # Compare columns and store differences
    diff_data = {}
    summary_data = {}
    for col in df1.columns:
        if col in df2.columns:
            diff_col_name = f"{col}_diff"
            diff_data[diff_col_name] = np.where(
                merged_df[col + "_file1"] != merged_df[col + "_file2"], True, False
            )
            summary_data[col] = np.sum(diff_data[diff_col_name])

    # Create a DataFrame of actual differences
    actual_diff_df = pd.DataFrame(diff_data, index=merged_df.index)
    actual_diff_df["row_number_file1"] = merged_df["row_number_file1"]
    actual_diff_df["row_number_file2"] = merged_df["row_number_file2"]
    actual_diff_df["_merge"] = merged_df["_merge"]

    # Reorder columns to move the _merge column to the end
    columns = actual_diff_df.columns.tolist()
    columns.remove("_merge")
    columns.append("_merge")
    actual_diff_df = actual_diff_df[columns]

    # Filter out rows with no differences
    actual_diff_df = actual_diff_df[actual_diff_df.any(axis=1)]

    # Replace True with actual values side by side
    for col in actual_diff_df.columns:
        if col != "_merge" and not col.startswith("row_number"):
            actual_diff_col = col.replace("_diff", "")
            file1_col = actual_diff_col + "_file1"
            file2_col = actual_diff_col + "_file2"
            actual_diff_df[col] = np.where(
                actual_diff_df[col],
                merged_df[file1_col].astype(str).replace("nan", "--")
                + " | "
                + merged_df[file2_col].astype(str).replace("nan", "--"),
                "--",
            )

    # Calculate the number of differences per column
    summary_df = pd.DataFrame(summary_data, index=["num_differences"]).transpose()
    summary_df.index.name = "column_name"

    # Get the unique row numbers for each file
    unique_rows_file1 = merged_df[merged_df["_merge"] == file1 + "_ONLY"].index.tolist()
    unique_rows_file2 = merged_df[merged_df["_merge"] == file2 + "_ONLY"].index.tolist()

    # Add unique row numbers to the summary DataFrame
    summary_df.loc[file1 + "_unique_rows", "num_differences"] = str(unique_rows_file1)
    summary_df.loc[file2 + "_unique_rows", "num_differences"] = str(unique_rows_file2)

    # Write the summary to a separate CSV file
    summary_file = os.path.join(
        os.path.dirname(output_file), f"summary_{os.path.basename(output_file)}"
    )
    summary_df.to_csv(summary_file, index_label="column_name")

    # Write the results to a new CSV file
    actual_diff_df.to_csv(output_file, index_label=id_cols)

def browse_file(entry_widget):
    file_path = filedialog.askopenfilename(
        filetypes=[
            ("CSV Files", "*.csv"),
            ("Excel Files", "*.xlsx"),
            ("All Files", "*.*"),
        ]
    )
    entry_widget.delete(0, tk.END)
    entry_widget.insert(0, file_path)

def run_comparison(
    file1_entry, file2_entry, output_format, progress_bar, summary_text, id_cols_entry
):
    file1_path = file1_entry.get()
    file2_path = file2_entry.get()

    if file1_path and file2_path:
        output_path = filedialog.asksaveasfilename(
            defaultextension=".{}".format(output_format.get()),
            filetypes=[
                ("CSV Files", "*.csv"),
                ("Excel Files", "*.xlsx"),
                ("All Files", "*.*"),
            ],
        )
        if output_path:
            id_cols = id_cols_entry.get().strip().split(",")
            progress_bar.start()
            compare_files(
                file1_path,
                file2_path,
                output_path,
                id_cols=id_cols,
                file_format=output_format.get(),
            )
            progress_bar.stop()
            progress_bar.grid_forget()

            summary_file = os.path.join(
                os.path.dirname(output_path), f"summary_{os.path.basename(output_path)}"
            )

            with open(summary_file, "r") as f:
                summary_text.delete(1.0, tk.END)
                summary_text.insert(tk.END, f.read())

            status_label.config(text="Comparison complete.")
        else:
            status_label.config(text="Output file not selected.")
    else:
        status_label.config(text="Input files not selected.")

def exit_app():
    root.destroy()

def reset(file1_entry, file2_entry, output_format, progress_bar, summary_text):
    file1_entry.delete(0, tk.END)
    file2_entry.delete(0, tk.END)
    output_format.set("csv")
    progress_bar.grid_forget()
    summary_text.delete(1.0, tk.END)
    status_label.config(text="")

def update_progress_bar(current, total):
    progress_percentage = (current / total) * 100
    progress_bar["value"] = progress_percentage
    progress_label.config(text=f"Progress: {progress_percentage:.1f}%")

root = tk.Tk()
root.title("CSV File Comparison Tool")
root.geometry("1000x800")
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)

mainframe = ttk.Frame(root, padding="10")
mainframe.grid(column=0, row=0, sticky=(tk.W, tk.E, tk.N, tk.S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(
    6, weight=1
)  # Add this line to configure the row containing the summary_text widget

file1_frame = ttk.LabelFrame(mainframe, text="First File")
file1_frame.grid(column=0, row=0, sticky=(tk.W, tk.E), padx=10, pady=10)
file1_frame.columnconfigure(1, weight=1)

file2_frame = ttk.LabelFrame(mainframe, text="Second File")
file2_frame.grid(column=0, row=1, sticky=(tk.W, tk.E), padx=10, pady=10)
file2_frame.columnconfigure(1, weight=1)

compare_files_btn = ttk.Button(mainframe, text="Compare Files", command=compare_files)
compare_files_btn.grid(column=0, row=2, padx=10, pady=10)

file2_format = tk.StringVar()
file2_format.set("csv")

file2_format_label = ttk.Label(file2_frame, text="File Format:")
file2_format_label.grid(column=3, row=0, padx=5, pady=5)

file2_format_combobox = ttk.Combobox(
    file2_frame, textvariable=file2_format, state="readonly"
)
file2_format_combobox["values"] = ("csv", "excel")
file2_format_combobox.grid(column=4, row=0, padx=5, pady=5)

file1_entry = ttk.Entry(file1_frame)
file1_entry.grid(column=1, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

file1_btn = ttk.Button(
    file1_frame, text="Browse", command=lambda: browse_file(file1_entry)
)
file1_btn.grid(column=2, row=0, padx=5, pady=5)

file2_entry = ttk.Entry(file2_frame)
file2_entry.grid(column=1, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

file2_btn = ttk.Button(
    file2_frame, text="Browse", command=lambda: browse_file(file2_entry)
)
file2_btn.grid(column=2, row=0, padx=5, pady=5)

file1_format = tk.StringVar()
file1_format.set("csv")

file1_format_label = ttk.Label(file1_frame, text="File Format:")
file1_format_label.grid(column=3, row=0, padx=5, pady=5)

file1_format_combobox = ttk.Combobox(
    file1_frame, textvariable=file1_format, state="readonly"
)
file1_format_combobox["values"] = ("csv", "excel")
file1_format_combobox.grid(column=4, row=0, padx=5, pady=5)

file1_identifier_label = ttk.Label(file1_frame, text="Identifier Column:")
file1_identifier_label.grid(column=5, row=0, padx=5, pady=5)

file1_identifier_entry = ttk.Entry(file1_frame)
file1_identifier_entry.grid(column=6, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

file2_identifier_label = ttk.Label(file2_frame, text="Identifier Column:")
file2_identifier_label.grid(column=5, row=0, padx=5, pady=5)

file2_identifier_entry = ttk.Entry(file2_frame)
file2_identifier_entry.grid(column=6, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

# Replace the following lines of code to create separate tooltips for the input fields and buttons
create_tooltip(file1_btn, "Click to select the first file")
create_tooltip(file2_btn, "Click to select the second file")
create_tooltip(file1_format_combobox, "Select the format of the first file")
create_tooltip(file2_format_combobox, "Select the format of the second file")
create_tooltip(file1_identifier_label, "Enter the identifier column for the first file")
create_tooltip(
    file2_identifier_label, "Enter the identifier column for the second file"
)
create_tooltip(compare_files_btn, "Click to compare the files")

# Modify the following lines of code to show the progress percentage and update the label text
progress_label = ttk.Label(mainframe, text="Progress: 0.0%")
progress_label.grid(column=0, row=4, sticky=(tk.W, tk.E), padx=10, pady=(0, 5))

id_cols_frame = ttk.Frame(mainframe)
id_cols_frame.grid(column=0, row=2, sticky=(tk.W, tk.E))
id_cols_frame.columnconfigure(1, weight=1)

id_cols_label = ttk.Label(id_cols_frame, text="Identifier Columns (comma separated):")
id_cols_label.grid(column=0, row=0, padx=5, pady=5)

id_cols_entry = ttk.Entry(id_cols_frame)
id_cols_entry.grid(column=1, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))
id_cols_entry.insert(0, "Ref,DateDue")

# Add the following lines below the id_cols_entry
control_col1 = tk.StringVar()
control_col1.set("Ref")

control_col2 = tk.StringVar()
control_col2.set("DateDue")

control_col1_label = ttk.Label(id_cols_frame, text="Control Column 1:")
control_col1_label.grid(column=2, row=0, padx=5, pady=5)

control_col1_entry = ttk.Entry(id_cols_frame, textvariable=control_col1)
control_col1_entry.grid(column=3, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

control_col2_label = ttk.Label(id_cols_frame, text="Control Column 2:")
control_col2_label.grid(column=4, row=0, padx=5, pady=5)

control_col2_entry = ttk.Entry(id_cols_frame, textvariable=control_col2)
control_col2_entry.grid(column=5, row=0, padx=5, pady=5, sticky=(tk.W, tk.E))

output_format_frame = ttk.Frame(mainframe)
output_format_frame.grid(column=0, row=3, sticky=(tk.W, tk.E))

output_format_label = ttk.Label(output_format_frame, text="Output Format:")
output_format_label.grid(column=0, row=0, padx=5, pady=5)

output_format = tk.StringVar()
output_format.set("csv")

output_format_combobox = ttk.Combobox(
    output_format_frame, textvariable=output_format, state="readonly"
)
output_format_combobox["values"] = ("csv", "excel")
output_format_combobox.grid(column=1, row=0, padx=5, pady=5)

compare_button = ttk.Button(
    mainframe,
    text="Compare Files",
    command=lambda: threading.Thread(
        target=run_comparison,
        args=(
            file1_entry,
            file2_entry,
            output_format,
            progress_bar,
            summary_text,
            id_cols_entry,
        ),
    ).start(),
)
compare_button.grid(column=0, row=3, padx=5, pady=10)

progress_bar = ttk.Progressbar(mainframe, mode="indeterminate")
progress_bar.grid(column=0, row=4, padx=5, pady=10, sticky=(tk.W, tk.E))

summary_label = ttk.Label(mainframe, text="Summary:")
summary_label.grid(column=0, row=5, padx=5, pady=5, sticky=tk.W)

summary_text = tk.Text(mainframe, wrap=tk.WORD, width=100, height=15)
summary_text.grid(column=0, row=6, padx=5, pady=5, sticky=(tk.W, tk.E))

status_label = ttk.Label(mainframe, text="")
status_label.grid(column=0, row=7, padx=5, pady=5)

reset_button = ttk.Button(
    mainframe,
    text="Reset",
    command=lambda: reset(
        file1_entry, file2_entry, output_format, progress_bar, summary_text
    ),
)
reset_button.grid(column=0, row=8, padx=5, pady=5)

exit_button = ttk.Button(mainframe, text="Exit", command=exit_app)
exit_button.grid(column=0, row=9, padx=5, pady=5)

root.mainloop()


import string
from pprint import pprint

# Q.  다음과 같은 문자열을 입력받았을 때, 어떤 알파벳이 가장 많이 포함되어 있는지 반환하시오
text = 'hello, this is sparta'

counter = {}
# 21 번 연산
for char in text:
    if not char.isalpha():
        continue
    if char in counter:
        counter[char] += 1
    else:
        counter[char] = 1
pprint(counter)

counter2 = {}
# 26 * 21 번 연산
for lo in string.ascii_lowercase:
    for char in text:
        if lo == char:
            if lo in counter2:
                counter2[lo] += 1
            else:
                counter2[lo] = 1
pprint(counter2)


import time
import cv2
import numpy as np

class OpenCVVideoPlayer:
    FrameCache = 500 # around 3 GB (500, un-compressed)

    def __init__(self, video_files, forced_resolution=None):
        self.current_time = None
        self.last_time = time.time()

        if len(video_files) < 1:
            raise Exception("Must specify at least one video file")

        self.video_files = video_files

        self.width = None
        self.height = None

        self.playing = False
        self.play_abs_position = 0.0
        self.play_video = 0
        self.play_speed = 1.0
        self.play_capture = None
        self.end_reached = False

        if forced_resolution is None:
            self.forced_width, self.forced_height = None, None
        else:
            self.forced_width, self.forced_height = forced_resolution

        self.total_frames = 0
        self.total_length = 0
        self.video_lengths = []
        self.video_offsets = [0.0]
        self.frame_offsets = [0]
        self.video_frames = []
        self.last_frame_img = None
        self.last_frame_idx = None

        self.cache_images = []
        self.cache_times = []
        self.cache_frames = []
        self.cache_offset = 0.0
        self.cache_pos = 0

        # get some basic properties
        # total length, frames
        for video_idx, video_file in enumerate(self.video_files):
            try:
                capture = cv2.VideoCapture(video_file)
            except Exception as e:
                #error loading
                raise Exception( "The file <" + video_file + "> could not be opened")

            if self.forced_width is None:
                capture_width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
                capture_height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
            else:
                capture_width = self.forced_width
                capture_height = self.forced_height

            if self.width is None:
                self.width = capture_width
                self.height = capture_height

                flag, self.last_frame_img = capture.read()

                dummy_get = capture.get(cv2.CAP_PROP_POS_MSEC)

                """
                self.cache_images.append(self.last_frame)
                self.cache_times.append(next_time)
                self.cache_frames.append(0)
                self.cache_offset = 0.0
                """
            else:
                if self.width != capture_width or self.height != capture_height:
                    raise Exception( "The resolutions of the specified video files do not match")

            # video_fps =  capture.get(cv.CV_CAP_PROP_FPS)
            video_frames = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))

            capture.set(cv2.CAP_PROP_POS_AVI_RATIO, 1.0)
            time_end = capture.get(cv2.CAP_PROP_POS_MSEC)
            # print((video_idx, time_end, video_frames, capture.get(cv2.CAP_PROP_POS_FRAMES)))

            video_length = time_end

            self.video_lengths.append(video_length)
            self.video_frames.append(video_frames)

            self.total_length += video_length
            self.total_frames += video_frames

            self.video_offsets.append(self.total_length)
            self.frame_offsets.append(self.frame_offsets[-1] + video_frames)

        self.current_capture = None

        self.black_frame = np.zeros((self.height, self.width, 3), dtype=np.uint8)

        self.frame_changed_callback = None

    def play(self):
        self.current_time = None
        self.last_time = time.time()

        self.playing = True
        self.end_reached = False

    def pause(self):
        self.playing = False

    def set_position_time(self, new_abs_position):
        # check if cache has to be cleaned (new position not in cache)
        raise Exception("Not implemented")

    def set_position_frame(self, new_abs_frame, notify_listeners):
        if new_abs_frame >= self.frame_offsets[-1]:
            new_abs_frame = self.frame_offsets[-1] - 2

        if new_abs_frame < 0:
            new_abs_frame = 0

        # first, check if the frame is still in the cache ...
        if len(self.cache_frames) > 0 and (self.cache_frames[0] <= new_abs_frame <= self.cache_frames[-1]):
            # already on cache, just move the time to the right frame
            offset = new_abs_frame - self.cache_frames[0]
            # adjust
            if offset > 0:
                self.play_abs_position = self.cache_times[offset - 1]
            else:
                # first element on cache ...
                self.play_abs_position = self.cache_offset

            self.cache_pos = offset
            self.last_frame_img = self.cache_images[self.cache_pos]
            self.last_frame_idx = self.cache_frames[self.cache_pos]
        else:
            # reset cache
            self.cache_frames = []
            self.cache_images = []
            self.cache_times = []
            self.cache_pos = 0

            # find desired video
            opened_video = self.play_video if self.current_capture is not None else -1
            self.play_video = 0

            while new_abs_frame > self.frame_offsets[self.play_video + 1]:
                self.play_video += 1

            #print("Jumping to video offset " + str(self.play_video))
            # open the video at desired frame
            offset = new_abs_frame - self.frame_offsets[self.play_video]
            if opened_video != self.play_video:
                self.current_capture = cv2.VideoCapture(self.video_files[self.play_video])

            self.current_capture.set(cv2.CAP_PROP_POS_FRAMES, offset)
            # update video location and cache start
            self.play_abs_position = self.current_capture.get(cv2.CAP_PROP_POS_MSEC) + self.video_offsets[self.play_video]
            self.cache_offset = self.play_abs_position

            #print("here")

            # read next frame
            self.last_frame_img, self.last_frame_idx = self.__extract_next_frame()

            #print("done")

        if self.frame_changed_callback is not None and notify_listeners:
            self.frame_changed_callback(int(new_abs_frame), self.play_abs_position)

        self.last_time = time.time()

    def __extract_next_frame(self):
        if self.current_capture is None:
            self.play_video = 0
            self.current_capture = cv2.VideoCapture(self.video_files[self.play_video])
            self.play_abs_position = 0.0

        # get the next frame ...
        flag = False
        while not flag:
            flag, next_frame = self.current_capture.read()
            if self.forced_width is not None and flag:
                next_frame = cv2.resize(next_frame, (self.forced_width, self.forced_height))

            if not flag:
                # failed to get frame from current capture... try opening next ...
                self.play_video += 1

                if self.play_video < len(self.video_files):
                    # open next
                    self.current_capture = cv2.VideoCapture(self.video_files[self.play_video])

                    flag, next_frame = self.current_capture.read()
                    if self.forced_width is not None and flag:
                        next_frame = cv2.resize(next_frame, (self.forced_width, self.forced_height))
                else:
                    self.end_reached = True
                    next_frame = None
                    break

        if next_frame is not None:
            # update cache ...
            last_time = self.current_capture.get(cv2.CAP_PROP_POS_MSEC) + self.video_offsets[self.play_video]
            frame_number = int(self.current_capture.get(cv2.CAP_PROP_POS_FRAMES)) - 1 + self.frame_offsets[self.play_video]

            self.cache_times.append(last_time)
            self.cache_images.append(next_frame)
            self.cache_frames.append(frame_number)

            while len(self.cache_times) > OpenCVVideoPlayer.FrameCache:
                self.cache_offset = self.cache_times[0]
                if self.cache_pos > 0:
                    self.cache_pos -= 1
                del self.cache_times[0]
                del self.cache_images[0]
                del self.cache_frames[0]
        else:
            frame_number = self.total_frames

        return next_frame, frame_number

    def __frame_in_cache(self, abs_time):
        if len(self.cache_times) == 0:
            return False

        return self.cache_offset <= abs_time <= self.cache_times[-1]

    def __get_cached_frame(self, abs_time):
        if self.end_reached:
            if len(self.cache_images) > 0:
                return self.cache_images[-1], self.cache_frames[-1]
            else:
                return self.black_frame, self.total_frames

        # assume forward movement only
        while self.cache_times[self.cache_pos] < abs_time:
            self.cache_pos += 1

        return self.cache_images[self.cache_pos], self.cache_frames[self.cache_pos]

    def get_frame(self):
        self.current_time = time.time()
        # in seconds ...
        delta = (self.current_time - self.last_time) * self.play_speed
        self.last_time = self.current_time
        #print(1.0 / delta)

        if self.playing:
            # update last frame ...
            # use milliseconds (just like opencv does)
            self.play_abs_position += delta * 1000.0

            # while desired frame not in cache ....
            while not self.__frame_in_cache(self.play_abs_position) and not self.end_reached:
                # ... update cache
                self.__extract_next_frame()

            # get frame
            self.last_frame_img, self.last_frame_idx = self.__get_cached_frame(self.play_abs_position)

            if self.frame_changed_callback is not None:
                if len(self.cache_frames) > 0:
                    self.frame_changed_callback(int(self.cache_frames[self.cache_pos]), self.cache_times[self.cache_pos])

        return self.last_frame_img, self.last_frame_idx

    def update_video_metrics(self, video_metrics):
        self.video_lengths = video_metrics["per_video_time"]
        self.video_frames = video_metrics["per_video_frames"]
        self.total_length = video_metrics["total_time"]
        self.total_frames = video_metrics["total_frames"]
        self.video_offsets = [0.0]
        self.frame_offsets = [0]

        for idx in range(len(self.video_frames)):
            self.video_offsets.append(self.video_offsets[-1] + self.video_lengths[idx])
            self.frame_offsets.append(self.frame_offsets[-1] + self.video_frames[idx])


# Wiener attack
# http://www.hit.bme.hu/~buttyan/Wiener/WienersAttack.pdf

import commonfucntions as common

# Solve Quadratic Equasion
def solve_quadratic_equation(n,phi):
    '''
    solve
    a*x^2+b*x + c
    and check if roots are n factors
    '''
    a = 1
    b = n - phi +1
    c = n

    d = (b**2) - (4*a*c)

    s1 = (-b-common.isqrt(abs(d)))//(2*a)
    s2 = (-b+common.isqrt(abs(d)))//(2*a)
    if s1*s2 == n:
        return (abs(s1),abs(s2))
    else:
        return False

# Start Wiener Algo
def solve_wiener(n,e):
    print("\nRefactoring N with Wiener Method:\n")
    # step 1: get e/n convergents
    for i in common.convergents_from_contfrac(common.rational_to_contfrac(e,n)):
        # step 2: check if d not trivial
        if i[1] <2 or i[1]%2==0:
            pass
        else:
            k = i[0]
            d = i[1]

            # Step 3: check if phi is whole value
            if (e*d-1)%k == 0:
                phi =  (e*d-1)//k
                # step4: solve the equasion x^2-(n-phi+1)*x + n and check if the root are n factors.
                pq =  solve_quadratic_equation(n,phi)
                if pq:
                    result = {}
                    result['p'] = pq[0]
                    result['q'] = pq[1]
                    print("\nWiener Method finished, N was refactored\n")
                    return result
                    break
    print("\nWiener Method finished, Failed\n")
    return False

if __name__ == "__main__":
    e = 468063471180295465090304528000264421835883255712360150238503461484286356674747
    n = 849904525105248028839166367198578395922976687042693061162002617712237437263151
    print('This is to test Wiener Algorithm')
    print( 'n = ',n)
    print( 'e = ',e)
    pq = solve_wiener(n,e)
    print ("p = ", pq['p'])
    print ("q = ", pq['q'])


import pandas as pd
import scrapy
import get_list
import des_prod

class SpiderRegistro(scrapy.Spider):
    name = 'registro'
    start_urls = [
        'https://registrosanitario.ispch.gob.cl/Ficha.aspx?RegistroISP='
    ]
    custom_settings = {
        # 'FEED_URI': 'cia.json',
        # 'FEED_FORMAT': 'json',
        'FEED_EXPORT_ENCODING': 'utf-8'
    }

    def parse(self, response):
        list_links = get_list.get_links()

        for link in list_links:
            # print(link)
            yield response.follow(link, callback=self.parse_link, cb_kwargs={'url': response.urljoin(link)})

    def parse_link(self, response, **kwargs):
        link = kwargs['url']
        descripcion = des_prod.des_prod(link)
        print(descripcion)


# -*- coding: utf-8 -*=

import numpy as np
from moving_object import Obstacle
from director.debugVis import DebugData

class World(object):

    """Base world."""

    def __init__(self, width, height):
        """Construct an empty world.

        Args:
            width: Width of the field.
            height: Height of the field.
        """
        self._data = DebugData()

        self._width = width
        self._height = height
        self._add_boundaries()

    def _add_boundaries(self):
        """Adds boundaries to the world."""
        self._x_max, self._x_min = self._width / 2, -self._width / 2
        self._y_max, self._y_min = self._height / 2, -self._height / 2

        corners = [
            (self._x_max, self._y_max, 0),  # Top-right corner.
            (self._x_max, self._y_min, 0),  # Bottom-right corner.
            (self._x_min, self._y_min, 0),  # Bottom-left corner.
            (self._x_min, self._y_max, 0)   # Top-left corner.
        ]

        # Loopback to begining.
        corners.append(corners[0])

        for start, end in zip(corners, corners[1:]):
            self._data.addLine(start, end, radius=0.2)

    def generate_obstacles(self, density=0.05, moving_obstacle_ratio=0.20,
                           seed=None):
        """Generates randomly scattered obstacles to the world.

        Args:
            density: Obstacle to world area ratio, default: 0.1.
            moving_obstacle_ratio: Ratio of moving to stationary obstacles,
                default: 0.2.
            seed: Random seed, default: None.

        Yields:
            Obstacle.
        """
        if seed is not None:
            np.random.seed(seed)

        field_area = self._width * self._height
        obstacle_area = int(field_area * density)

        bounds = self._x_min, self._x_max, self._y_min, self._y_max
        while obstacle_area > 0:
            radius = np.random.uniform(1.0, 3.0)
            center_x_range = (self._x_min + radius, self._x_max - radius)
            center_y_range = (self._y_min + radius, self._y_max - radius)
            center_x = np.random.uniform(*center_x_range)
            center_y = np.random.uniform(*center_y_range)
            theta = np.random.uniform(0., 360.)
            obstacle_area -= np.pi * radius ** 2

            # Only some obstacles should be moving.
            if np.random.random_sample() >= moving_obstacle_ratio:
                velocity = 0.0
            else:
                velocity = np.random.uniform(-30.0, 30.0)

            obstacle = Obstacle(velocity, radius, bounds)
            obstacle.x = center_x
            obstacle.y = center_y
            obstacle.theta = np.radians(theta)
            yield obstacle

    def to_polydata(self):
        """Converts world to visualizable poly data."""
        return self._data.getPolyData()


""" PyYelpAPI module reads data from Yelp business API and insert data to sqlite3 database"""
import requests
import sqlite3
from pathlib import Path
import os
import configparser
import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)

class PyYelpAPI:

    def get_yelp_api_restaurant_data(self):
        """ Reads data from Yelp business endpoint for all Restaurant in BOS location"""
        thisfolder = os.path.dirname(os.path.abspath(__file__))
        initfile = os.path.join(thisfolder, r'configuration.txt')
        logging.info(logging.getLoggerClass().root.handlers[0].baseFilename)
        logging.info(f"Current folder : {thisfolder}")
        config = configparser.ConfigParser()
        config.read(initfile)
        url = config.get('YELP-API-INFO', 'url')
        api_key = config.get('YELP-API-INFO', 'api_key')
        logging.info(url)
        logging.info(api_key)

        headers_dict = {
            "Authorization": "Bearer "+api_key
        }
        params_dict = {
            "term": "Restaurant",
            "location": "BOS"
        }
        return requests.get(url, headers=headers_dict, params=params_dict)

    def insert_api_data_to_table(self, response):
        """ insert data into Resturant table by reading YELP API JSON response """
        try:
            businesses_list = response.json()["businesses"]
            with sqlite3.connect("db.sqllite3") as connection_ref:
                command = "INSERT INTO RESTAURANT VALUES (?, ? , ?)"

                for each_business_item in businesses_list:
                    name = each_business_item["name"]
                    review_count = each_business_item["review_count"]
                    phone = each_business_item["phone"]
                    logging.info(
                        f"Data inserted into RESTAURANT table is: {name} , {review_count}, {phone}")

                    data = (name, review_count, phone)
                    connection_ref.execute(command, data)
                    connection_ref.commit()
                return True
        except Exception as ex:
            logging.error("Something went wrong during data insertion")
            logging.error(ex)
            return False

response = PyYelpAPI().get_yelp_api_restaurant_data()
PyYelpAPI().insert_api_data_to_table(response)


import unittest
from problem3 import largestPrimeFactor

class MyTestCase(unittest.TestCase):
    def test_largestPrimeFactor(self):
        testdata = {2:2, 3:3, 5:5, 7: 7, 13195: 29, 600851475143: 6857}
        for key in testdata:
            self.assertEqual(largestPrimeFactor(key),testdata[key])

if __name__ == '__main__':
    unittest.main()


import inspect
import unittest

import numpy as np

from coral_model import core
from coral_model.core import CONSTANTS, Coral, Light, Flow, Temperature, PROCESSES, Photosynthesis, \
    Calcification, Morphology, Dislodgement, Recruitment
from coral_model.environment import Processes, Constants
from coral_model.utils import DataReshape

def decorator(test):
    def wrapper(self):
        core.RESHAPE = DataReshape((1, 1))
        core.PROCESSES = Processes()
        core.CONSTANTS = Constants(Processes())
        test(self)
    wrapper.__name__ = test.__name__
    return wrapper

def set_shape(cls):
    for name, method in inspect.getmembers(cls):
        if name.startswith('test_'):
            setattr(cls, name, decorator(method))
    return cls

@set_shape
class TestCoral(unittest.TestCase):

    def test_default(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertEqual(coral.Csp, 1)

    def test_input_single(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertEqual(coral.dc, .2)
        self.assertEqual(coral.hc, .3)
        self.assertEqual(coral.bc, .1)
        self.assertEqual(coral.tc, .15)
        self.assertEqual(coral.ac, .3)

    def test_input_multiple(self):
        coral = Coral([.2, .2], [.3, .3], [.1, .1], [.15, .15], [.3, .3])
        self.assertEqual(coral.dc[0], .2)
        self.assertEqual(coral.hc[0], .3)
        self.assertEqual(coral.bc[0], .1)
        self.assertEqual(coral.tc[0], .15)
        self.assertEqual(coral.ac[0], .3)

    def test_representative_diameter(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertAlmostEqual(float(coral.dc_rep), .15)

    def test_morphological_ratios(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertAlmostEqual(float(coral.rf), 1.5)
        self.assertAlmostEqual(float(coral.rp), .5)
        self.assertAlmostEqual(float(coral.rs), 2/3)

    def test_coral_volume(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertAlmostEqual(coral.volume, .0058904862254808635)

    def test_vegetation_density(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertAlmostEqual(coral.as_vegetation_density, 3.3333333333333335)

    def test_coral_cover(self):
        coral = Coral(.2, .3, .1, .15, .3)
        self.assertEqual(coral.cover, 1)
        coral = Coral([.2, .2], [.3, .3], [.1, .1], [.15, .15], [.3, .3])
        self.assertEqual(coral.cover[0], 1)
        self.assertEqual(coral.cover[1], 1)

@set_shape
class TestLight(unittest.TestCase):

    def test_initiation(self):
        light = Light(600, .1, 5)
        self.assertEqual(light.I0, 600)
        self.assertEqual(light.Kd, .1)
        self.assertEqual(light.h, 5)

    def test_representative_light(self):
        light = Light(600, .1, 5)
        # base light
        coral = Coral(.2, .3, .1, .15, .3)
        light.rep_light(coral)
        answer = 217.0490558
        self.assertAlmostEqual(float(coral.light), answer)
        # no base light
        coral = Coral(.4, .3, .2, .15, .3)
        light.rep_light(coral)
        answer = 253.8318634
        self.assertAlmostEqual(float(coral.light), answer)

    def test_coral_biomass(self):
        light = Light(600, .1, 5)
        # base light
        coral = Coral(.2, .3, .1, .15, .3)
        light.biomass(coral)
        answer = .14287642
        self.assertAlmostEqual(float(coral.Bc), answer)
        # no base light
        coral = Coral(.4, .3, .2, .15, .3)
        light.biomass(coral)
        answer = .314159265
        self.assertAlmostEqual(float(coral.Bc), answer)

    def test_base_light(self):
        light = Light(600, .1, 5)
        # base light
        coral = Coral(.2, .3, .1, .15, .3)
        result = light.base_light(coral)
        answer = .05478977
        self.assertAlmostEqual(float(result), answer)
        # no base light
        coral = Coral(.4, .3, .2, .15, .3)
        result = light.base_light(coral)
        answer = 0
        self.assertAlmostEqual(float(result), answer)

    def test_side_correction(self):
        light = Light(600, .1, 5)
        coral = Coral(.2, .3, .1, .15, .3)
        max_thetas = np.linspace(0, np.pi)
        for theta in max_thetas:
            CONSTANTS.theta_max = theta
            result = light.side_correction(coral)
            self.assertLess(result, 1)

@set_shape
class TestFlow(unittest.TestCase):

    def test_initiation(self):
        flow = Flow(.1, .1, 5, 4)
        self.assertEqual(flow.uc[0], .1)
        self.assertEqual(flow.uw[0], .1)
        self.assertEqual(flow.h, 5)
        self.assertEqual(flow.Tp[0], 4)

    def test_wave_attenuation(self):
        # input array
        diameter = [.1, .2, .4]     # [m]
        height = .3                 # [m]
        distance = [.3, .4, .6]     # [m]
        velocity = .05              # [m s-1]
        period = 4                  # [s]
        depth = .75                 # [m]

        # answers
        answer = [
            .73539733818684030,
            .47628599416211803,
            .20277038395777466,
        ]

        for i in range(3):
            wac = Flow.wave_attenuation(
                diameter=diameter[i],
                height=height,
                distance=distance[i],
                velocity=velocity,
                period=period,
                depth=depth,
                wac_type='wave',
            )
            self.assertAlmostEqual(float(wac), answer[i], delta=.1)

@set_shape
class TestTemperature(unittest.TestCase):

    def test_initiation(self):
        temperature = Temperature(300)
        self.assertEqual(temperature.T, 300)

    def test_coral_temperature(self):
        temperature = Temperature(300)
        coral = Coral(.2, .3, .1, .15, .3)
        coral.delta_t = .001
        coral.light = 600
        temperature.coral_temperature(coral)
        self.assertAlmostEqual(float(coral.temp), 300.00492692)

    def test_no_tme(self):
        core.PROCESSES.tme = False
        temperature = Temperature(300)
        coral = Coral(.2, .3, .1, .15, .3)
        coral.delta_t = .001
        coral.light = 600
        temperature.coral_temperature(coral)
        self.assertAlmostEqual(float(coral.temp), 300)

@set_shape
class TestPhotosynthesis(unittest.TestCase):

    def test_initiation(self):
        photosynthesis = Photosynthesis(600, False)
        self.assertEqual(float(photosynthesis.I0), 600)
        self.assertFalse(photosynthesis.first_year)
        self.assertEqual(float(photosynthesis.pld), 1)
        self.assertEqual(float(photosynthesis.ptd), 1)
        self.assertEqual(float(photosynthesis.pfd), 1)

    def test_photosynthetic_light_dependency(self):
        photosynthesis = Photosynthesis(600, False)
        coral = Coral(.2, .3, .1, .15, .3)
        coral.light = 600
        photosynthesis.light_dependency(coral, 'qss')
        self.assertAlmostEqual(float(photosynthesis.pld), .90727011)

    def test_photosynthetic_flow_dependency(self):
        photosynthesis = Photosynthesis(600, False)
        coral = Coral(.2, .3, .1, .15, .3)
        coral.ucm = .1
        photosynthesis.flow_dependency(coral)
        self.assertAlmostEqual(float(photosynthesis.pfd), .94485915)
        core.PROCESSES.pfd = False
        photosynthesis.flow_dependency(coral)
        self.assertEqual(float(photosynthesis.pfd), 1)

@set_shape
class TestPopulationStates(unittest.TestCase):
    # TODO: Write tests for the determination of the population states
    pass

@set_shape
class TestCalcification(unittest.TestCase):

    def test_initiation(self):
        calcification = Calcification()
        self.assertEqual(float(calcification.ad), 1)

    def test_calcification_rate(self):
        calcification = Calcification()
        coral = Coral(.2, .3, .1, .15, .3)
        coral.pop_states = np.array([[[[1]]]])
        coral.photo_rate = 1
        omegas = np.linspace(1, 5, 4)
        answer = [
            .28161333,
            .38378897,
            .42082994,
            .43996532
        ]
        for i, omega in enumerate(omegas):
            calcification.calcification_rate(coral, omega)
            self.assertAlmostEqual(float(coral.calc), answer[i])

@set_shape
class TestMorphology(unittest.TestCase):

    def test_initiation(self):
        morphology = Morphology(1, 600)
        self.assertEqual(morphology.calc_sum, 1)
        self.assertEqual(morphology.I0, 600)
        self.assertEqual(morphology.dt_year, 1)
        self.assertEqual(morphology.vol_increase, 0)

        self.assertIsNone(morphology.rf_optimal)
        self.assertIsNone(morphology.rp_optimal)
        self.assertIsNone(morphology.rs_optimal)

    def test_calc_sum_init1(self):
        morphology = Morphology([1, 1], 600)
        answer = [1, 1]
        for i, val in enumerate(answer):
            self.assertEqual(morphology.calc_sum[i], val)

    def test_optimal_ratios(self):
        morphology = Morphology(1, DataReshape().variable2matrix(600, 'time'))
        coral = Coral(.2, .3, .1, .15, .3)
        coral.light = DataReshape().variable2matrix(600, 'time')
        coral.ucm = DataReshape().variable2array(.1)

        ratios = ('rf', 'rp', 'rs')
        answers = [
            .2,
            .475020813,
            .302412911,
        ]

        for i, ratio in enumerate(ratios):
            setattr(morphology, f'{ratio}_optimal', coral)
            self.assertAlmostEqual(float(getattr(morphology, f'{ratio}_optimal')), answers[i])

    def test_volume_increase(self):
        morphology = Morphology(1, DataReshape().variable2matrix(600, 'time'))
        coral = Coral(.2, .3, .1, .15, .3)
        coral.Bc = DataReshape().variable2matrix(.3, 'time')
        morphology.delta_volume(coral)
        self.assertAlmostEqual(float(morphology.vol_increase), 8.4375e-6)

    def test_morphology_update(self):
        morphology = Morphology(1, DataReshape().variable2matrix(600, 'time'))
        coral = Coral(.2, .3, .1, .15, .3)
        coral.light = DataReshape().variable2matrix(600, 'time')
        coral.ucm = DataReshape().variable2array(.1)
        coral.Bc = DataReshape().variable2matrix(.3, 'time')
        # morphology.delta_volume(coral)
        for ratio in ('rf', 'rp', 'rs'):
            setattr(morphology, f'{ratio}_optimal', coral)
        morphology.update(coral)
        self.assertAlmostEqual(float(coral.rf), 1.498140551)
        self.assertAlmostEqual(float(coral.rp), .499964271)
        self.assertAlmostEqual(float(coral.rs), .666145658)
        self.assertAlmostEqual(float(coral.volume), .005898924)

@set_shape
class TestDislodgement(unittest.TestCase):

    def test_initiation(self):
        dislodgement = Dislodgement()
        self.assertIsNone(dislodgement.dmt)
        self.assertIsNone(dislodgement.csf)
        self.assertIsNone(dislodgement.survival)

    def test_dmt1(self):
        dislodgement = Dislodgement()
        coral = Coral(.2, .3, .1, .15, .3)
        coral.um = 0
        dislodgement.dislodgement_mechanical_threshold(coral)
        self.assertEqual(dislodgement.dmt, 1e20)

    def test_dmt2(self):
        dislodgement = Dislodgement()
        coral = Coral(.2, .3, .1, .15, .3)
        coral.um = .5
        dislodgement.dislodgement_mechanical_threshold(coral)
        self.assertAlmostEqual(float(dislodgement.dmt), 780.487805, delta=1e-6)

    def test_dmt3(self):
        dislodgement = Dislodgement()
        coral = Coral([.2, .2], [.3, .3], [.1, .1], [.15, .15], [.3, .3])
        coral.um = [0, .5]
        dislodgement.dislodgement_mechanical_threshold(coral)
        answers = [1e20, 780.487805]
        for i, ans in enumerate(answers):
            self.assertAlmostEqual(float(dislodgement.dmt[i]), ans, delta=1e-6)

    def test_csf1(self):
        dislodgement = Dislodgement()
        coral = Coral(.2, .3, .1, .15, .3)
        dislodgement.colony_shape_factor(coral)
        self.assertAlmostEqual(float(dislodgement.csf), 40.1070456591576246)

    def test_csf2(self):
        dislodgement = Dislodgement()
        coral = Coral([.2, 0], [.3, 0], [.1, 0], [.15, 0], [.3, 0])
        dislodgement.colony_shape_factor(coral)
        answers = [40.1070456591576246, 0]
        for i, ans in enumerate(answers):
            self.assertAlmostEqual(float(dislodgement.csf[i]), ans)

@set_shape
class TestRecruitment(unittest.TestCase):

    def test_spawning_cover1(self):
        recruitment = Recruitment()
        coral = Coral(.2, .3, .1, .15, .3)
        coral.pop_states = np.array(
            [
                [
                    [1, 0, 0, 0]
                ]
            ]
        )
        result = recruitment.spawning(coral, 'P')
        self.assertEqual(float(result), 0)

    def test_spawning_cover2(self):
        recruitment = Recruitment()
        coral = Coral(.2, .3, .1, .15, .3)
        coral.pop_states = np.array(
            [
                [
                    [.5, 0, 0, 0]
                ]
            ]
        )
        result = recruitment.spawning(coral, 'P')
        self.assertAlmostEqual(float(result), 2.5e-5)

if __name__ == '__main__':
    core.RESHAPE = DataReshape((1, 1))
    unittest.main()


import csv
import os

def fix_csv(inputfn, outputfn):
  output_rows = []
  lastrow = None
  first = False
  with open(inputfn) as inf:
    csvf = csv.reader(inf)
    for row in csvf:
      combined = False
      if first:
        # This is dumb
        first=True
        continue
      if lastrow:
        if lastrow[0].strip() and lastrow[1].strip():
          # print(lastrow)
          # print(row)

          if not row[1].strip() and not row[2].strip():
            combined = True
            lastrow[0] += " " + row[0]
            if len(row) > 3 and row[3].strip():
              lastrow[3] += '\n'+row[3]
            if len(row) > 4 and row[4].strip():
              lastrow[4] += '\n'+row[4]
            if len(row) > 5 and row[5].strip():
              lastrow[5] += '\n'+row[5]
        # print(lastrow)
        # print("---")
        output_rows.append(lastrow)
        if combined:
          lastrow = None
        else:
          lastrow=row
      else:
        lastrow=row

  with open(outputfn, 'w', encoding="utf8") as outf:
    writer = csv.writer(outf)
    writer.writerows(output_rows)

  # with open(outputfn, 'w') as outf:
  #   outf.writelines(output_rows)

if __name__ == "__main__":
  import sys
  inputfn, outputfn = sys.argv[1:]

  fix_csv(inputfn, outputfn)


from datetime import datetime
from ckeditor.fields import RichTextField
from django.db import models

# features_choices = (
#     ('Круиз-контроль', 'Круиз-контроль'),
#     ('Аудио интерфейс', 'Аудио интерфейс'),
#     ('Подушки безопасности', 'Подушки безопасности'),
#     ('Кондиционер', 'Кондиционер'),
#     ('Подогрев сидений', 'Подогрев сидений'),
#     ('Аварийная система', 'Аварийная система'),
#     ('Парковщик', 'Парковщик'),
#     ('Усилитель рулевого управления', 'Усилитель рулевого управления'),
#     ('Камера заднего вида', 'Камера заднего вида'),
#     ('Непосредственный Впрыск Топлива', 'Непосредственный Впрыск Топлива'),
#     ('Автоматический Запуск Остановка', 'Автоматический Запуск Остановка'),
#     ('Ветроотражатель', 'Ветроотражатель'),
#     ('Телефонная трубка Bluetooth', 'Телефонная трубка Bluetooth'),
# )

# Create your models here.

class Features(models.Model):
    title = models.CharField(max_length=100, verbose_name='особенности')

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Особиность'
        verbose_name_plural = 'Особиности'

class Car(models.Model):
    state_choice = (
        ('AL', 'Alabama'),
        ('AK', 'Alaska'),
        ('AZ', 'Arizona'),
        ('AR', 'Arkansas'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DE', 'Delaware'),
        ('DC', 'District Of Columbia'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('HI', 'Hawaii'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('IA', 'Iowa'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('ME', 'Maine'),
        ('MD', 'Maryland'),
        ('MA', 'Massachusetts'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MS', 'Mississippi'),
        ('MO', 'Missouri'),
        ('MT', 'Montana'),
        ('NE', 'Nebraska'),
        ('NV', 'Nevada'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NY', 'New York'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VT', 'Vermont'),
        ('VA', 'Virginia'),
        ('WA', 'Washington'),
        ('WV', 'West Virginia'),
        ('WI', 'Wisconsin'),
        ('WY', 'Wyoming'),
    )
    year_choice = []
    for r in range(2000, (datetime.now().year+1)):
        year_choice.append((r, r))

    door_choices = (
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
        ('6', '6'),
    )

    car_title = models.CharField(max_length=255, verbose_name='Загаловак')
    state = models.CharField(choices=state_choice, max_length=100, verbose_name='города')
    city = models.CharField(max_length=100, verbose_name='Город')
    color = models.CharField(max_length=100, verbose_name='Цвет')
    model = models.CharField(max_length=100, verbose_name='Модель')
    year = models.IntegerField(('year'), choices=year_choice)
    condition = models.CharField(max_length=100, verbose_name='состояние')
    price = models.IntegerField(verbose_name='Цена')
    old_qina = models.IntegerField(verbose_name='Старая цина', blank=True, default=0)
    description = RichTextField()
    car_photo = models.ImageField(upload_to='car_photos/%Y/%m/%d/', verbose_name='Фото авто')
    car_photo_1 = models.ImageField(upload_to='car_photos/%Y/%m/%d/', blank=True, verbose_name='Фото авто')
    car_photo_2 = models.ImageField(upload_to='car_photos/%Y/%m/%d/', blank=True, verbose_name='Фото авто')
    car_photo_3 = models.ImageField(upload_to='car_photos/%Y/%m/%d/', blank=True, verbose_name='Фото авто')
    car_photo_4 = models.ImageField(upload_to='car_photos/%Y/%m/%d/', blank=True, verbose_name='Фото авто')
    features = models.ManyToManyField(Features, verbose_name='особенности')
    body_style = models.CharField(max_length=100, verbose_name='Тип автомабиля')
    engine = models.CharField(max_length=100, verbose_name='двигатель')
    transmission = models.CharField(max_length=100, verbose_name='коробка передач')
    interior = models.CharField(max_length=100, verbose_name='интерьер')
    miles = models.IntegerField(verbose_name='миль')
    doors = models.CharField(choices=door_choices, max_length=10, verbose_name='двери')
    passengers = models.IntegerField(verbose_name='пассажиры')
    vin_no = models.CharField(max_length=100, verbose_name='Номер')
    milage = models.IntegerField(verbose_name='пробег')
    fuel_type = models.CharField(max_length=50, verbose_name='тип топлива')
    fuel_consumption = models.CharField(max_length=255, verbose_name='Расход топлива', blank=True)
    on_of_owners = models.CharField(max_length=100, verbose_name='от имени владельцев')
    is_featured = models.BooleanField(default=False,verbose_name='Опубликовано')
    created_data = models.DateTimeField(default=datetime.now, blank=True, verbose_name='Дата создания обявления')

    class Meta:
        verbose_name = 'Авто'
        verbose_name_plural = 'Автомобили'

    def __str__(self):
        return self.car_title


from math import sqrt

def func(n=100, m=200):
    res = []
    if n == 1:
        res = [2] + [num for num in range(2, m) if
                     num % 2 != 0 and 0 not in [num % i for i in range(2, int(sqrt(num)) + 1)]]
    if n >= 2:
        res = [num for num in range(n, m) if num % 2 != 0 and 0 not in [num % i for i in range(2, int(sqrt(num)) + 1)]]
    print(res)

if __name__ == '__main__':
    func()


'''Suponha que você precise programar uma máquina de autoatendimento (ATM).
O usuário entrará com um valor inteiro (qualquer inteiro) correspondente ao
valor que deseja sacar, e a ATM precisa decidir como distribuir as cédulas
para o usuário. O programa deve sempre priorizar as cédulas de maior valor.
Considere que as únicas cédulas disponíveis são as de 20, 10, 5, 2 e 1.

ENTRADA:
Valor a ser sacado. Tem que ser inteiro.

SAÍDA:
Quantidade de cédulas de 20,10,5,2,1 (nesta ordem, cada quantidade em uma linha).

Ex.:
Suponha que um cliente queira sacar R$ 123.
A ATM deve fornecer 6 cédulas de 20,
0 de 10, 0 de 5, 1 de 2 e 1 de 1.

Logo, a entrada será:
123

E a saída do seu programa deve ser:
6
0
0
1
1

Apenas as quantidades devem ser mostradas, conforme mostrado acima.
DICA:
Teste com vários valores manualmente e no papel antes de
tentar desenvolver o seu algoritmo. Isso ajuda a pensar
na solução.'''

saque = int(input())

vinte = int(saque/20)
saque = saque % 20

dez = int(saque/10)
saque = saque % 10

cinco = int(saque/5)
saque = saque % 5

dois = int(saque/2)
saque = saque % 2

um = saque

print ('\n', vinte, '\n', dez, '\n', cinco, '\n', dois, '\n', um)

Unidade 2 - Estruturas Condicionais/condicionais4.py


import sys
import numpy as np
import pandas as pd
from manipularArquivo import *
from removerRepetidos import *

arquivo=manipularArquivo()
alfabeto = arquivo[0]
estados = arquivo[1]
inicial = arquivo[2]
final = arquivo[3]
transicoes = arquivo[4]

## Vefificações do arquivo
if not ((len(estados)*2) == len(transicoes)):
    sys.exit("Numero incorreto de transicoes")
if (len(inicial) > 1):
    sys.exit("Mais de um estado inicial")
if (len(final) > len(estados)):
    sys.exit("Numero de estados finais incorreto")

count= np.full((len(estados)), 0)
for t in transicoes:
    count[t[0]]= count[t[0]] + 1
for c in count:
    if(c > 2):
        sys.exit("Numero de transições saindo de um mesmo estado maior que o permitido")
    if(c < 2):
        sys.exit("Numero de transições saindo de um mesmo estado menor que o permitido")

## Criando Matriz para manipulação
matrizTamanho = len(estados)
matriz = np.full((matrizTamanho,matrizTamanho), 0)
print("\n Matriz vazia com a quantidade de espaços variando de acordo com os numero de estados. \n",matriz,"\n")

## Setando 1 para todos os pares (L,C) onde L é final e C não é final.
## Setando 0 se L e C são Finais.
for idx,x in enumerate(matriz, start=0):
        for idy,y in enumerate(matriz, start=0):
            for q in final:
                if( q == idx) and (q != idy):
                    matriz[idy][idx]= 1
                if(q == idy) and (q != idx):
                    matriz[idy][idx]= 1
            if idx in final:
                if idy in final:
                   matriz[idy][idx]= 0
print("\n Setando 1 para todos os pares (L,C) onde L é final e C não é final. \n",matriz,"\n")

## Verifica onde ainda é 0 na matriz e ver se (L,C) onde [(L,x),(C,x)] é 1 se for então (L,C) tambés vira 1.

tempA=0
tempB=0
for idx,x in enumerate(matriz, start=0):
        for idy,y in enumerate(matriz, start=0):
            if(matriz[idx][idy] == 0):
                for t in transicoes:
                    if(t[0] == idx  and t[2] == 0):
                        tempA = t[1]
                    if(t[0] == idy  and t[2] == 0):
                        tempB = t[1]
                for t in transicoes:
                    if(t[0] == idx  and t[2] == 1):
                        tempA = t[1]
                    if(t[0] == idy  and t[2] == 1):
                        tempB = t[1]
                if(matriz[tempA][tempB] == 1):
                    matriz[idx][idy]=1

print("Verifica onde ainda é 0 na matriz e ver se (L,C) onde [(L,x),(C,x)] é 1 se for então (L,C) tambés vira 1. \n",matriz,"\n")

## Criando matriz ignorando a diagonal superior
matrizDiag = np.tri(matrizTamanho,matrizTamanho)
for idx,x in enumerate(matrizDiag, start=0):
        for idy,y in enumerate(matrizDiag, start=0):
            if(matrizDiag[idx][idy] == 0):
                matriz[idx][idy] = 999
            if(idx == idy):
                matriz[idx][idy] = 999

print("Nova matriz ignorando a diagonal superior. \n",matriz,"\n")

## Lista onde é 0 na Matriz
listJuntar = []
for idx,x in enumerate(matriz, start=0):
        for idy,y in enumerate(matriz, start=0):
            if(matriz[idx][idy] == 0):
                listJuntar.append([idy,idx])

print ("Criando uma nova lista onde é 0 na Matriz",listJuntar,"\n")

estadosQ = []
estadosQfinal = []
for q in estados:
    for x in listJuntar:
        if(x[0] == q or x[1] == q):
            estadosQ.append(x[0])
            estadosQ.append(x[1])
            for x in listJuntar:
                if(x[0] == q or x[1] == q):
                    estadosQ.append(x[0])
                    estadosQ.append(x[1])
    estadosQt = remove_repetidos(estadosQ)
    if not (estadosQt == []):
        estadosQfinal.append(estadosQt)
    else:
        estadosQfinal.append([q])
    estadosQ.clear()

estadosQfinal = remove_repetidos(estadosQfinal)

print ("Novo Conjunto de estados finais \n",estadosQfinal,"\n")

transicoesQ = []
transicoesQfinal = [[]]
nEstado=0
novoEstados=[]
estadosFinais=[]
estadoInicialNovo=[]
for e in estadosQfinal:
    for ee in e:
        for t in transicoes:
            if (ee == t[0]):
                transicoesQ.append(t)
        novoEstados.append(nEstado)
    for t in transicoesQ:
        for idd,tDelete in enumerate(transicoesQ, start=0):
            if(t != tDelete):
                if(t[2] == tDelete[2]):
                    transicoesQ.pop(idd)
    for es in e:
        if es in final:
            estadosFinais.append(nEstado)
    for ef in e:
        if ef in inicial:
            estadoInicialNovo.append(nEstado)
    qe= ['q'+str(i) for i in e]
    nEstado += 1
    print (nEstado,"° estado. Junção do(s) estado(s) ",qe)

    print(transicoesQ,"\n")
    if not (transicoesQ == []):
        transicoesQfinal.append([transicoesQ[0],transicoesQ[1]])
    transicoesQ.clear()
if transicoesQfinal[0]== []:
    transicoesQfinal.pop(0)

for tx,t in enumerate(transicoesQfinal, start=0):
    for ti in t:
        ti[0]= tx

print("\n Transicoes Finais:")

estadosFinais= remove_repetidos(estadosFinais)
estadosFinais= ['q'+str(i) for i in estadosFinais]
estadoInicialNovo= ['q'+str(i) for i in estadoInicialNovo]

matrizFinal = np.full((nEstado,nEstado), "")

for t in  transicoesQfinal:
    for tt in t:
        tt[0]='q'+str(tt[0])
        tt[1]= novoEstados[tt[1]]
        tt[1]='q'+str(tt[1])
        tt[2]= alfabeto[tt[2]]
    if(tt[0] in estadosFinais):

        x1=int((t[0][0])[1:])
        x2=int((t[0][1])[1:])
        y1=int((t[1][0])[1:])
        y2=int((t[1][1])[1:])
        matrizFinal[x1][x2]=matrizFinal[x1][x2]+ t[0][2]
        matrizFinal[y1][y2]=matrizFinal[y1][y2]+ t[1][2]

        print (t," Estado Final",end="")
        if(tt[0] in estadoInicialNovo):

            print ("e Estado Inicial")
        else:
            print(" ")
    else:
        x1=int((t[0][0])[1:])
        x2=int((t[0][1])[1:])
        y1=int((t[1][0])[1:])
        y2=int((t[1][1])[1:])
        matrizFinal[x1][x2]=matrizFinal[x1][x2]+ t[0][2]
        matrizFinal[y1][y2]=matrizFinal[y1][y2]+ t[1][2]

        print (t,end=" ")
        if(tt[0] in estadoInicialNovo):
            print ("Estado Inicial")
        else:
            print(" ")

DF = pd.DataFrame(matrizFinal)
DF.to_csv("tabelaParaVizualizacao.csv")


import ctypes
import _ctypes
import time
import numpy as np
import itertools
import os

def isLoaded(lib):
  libp = os.path.abspath(lib)
  ret = os.system("lsof -p %d | grep %s" % (os.getpid(), libp))
  print(ret)
  return (ret == 0)

def unloadLib(handle, path):
  tries = 0
  while(isLoaded(path)):
    tries += 1
    _ctypes.dlclose(handle)
    print('Unloading, try %d' % tries)
    if(tries > 150):
      break

class QBladeAdapter:
  def __init__(self, project="../sample_projects/NREL_5MW_STR.wpa"):
    self.project = project
    self._qbladeLib = None

    print("loading qblade library")
    qbladeLib = ctypes.CDLL('../qblade_build/libQBlade.so')
    self._qbladeLib = qbladeLib
    self.map_functions(qbladeLib)

    print("creating qblade instance")
    self._qbladeLib._Z14createInstancev()
    self.load_default_project()

    print("qblade init done")

  def map_functions(self, qbladeLib):
    self._createInstance = qbladeLib._Z14createInstancev
    self._initializeSimulation = qbladeLib._Z20initializeSimulationi
    self._loadProject = qbladeLib._Z11loadProjectPc
    self._loadProject.argtypes = [ctypes.c_char_p]
    self._storeProject = qbladeLib._Z12storeProjectPc
    self._storeProject.argtypes = [ctypes.c_char_p]
    self._setControlVars = qbladeLib._Z14setControlVarsPd
    self._setControlVars.argtypes = [ctypes.POINTER(ctypes.c_double)]
    self._getControlVars = qbladeLib._Z14getControlVarsPd
    self._getControlVars.argtypes = [ctypes.POINTER(ctypes.c_double)]
    self._advanceSingleTimestep = qbladeLib._Z21advanceSingleTimestepv

  def del_functions(self):
    del self._createInstance
    del self._initializeSimulation
    del self._loadProject
    del self._storeProject
    del self._setControlVars
    del self._getControlVars
    del self._advanceSingleTimestep

  def load_default_project(self):
    x = ctypes.c_char_p(bytes(self.project, 'utf-8'))
    print("loading qblade project")
    self._loadProject(x)
    self.steps_since_reload = 0

  def reset(self):
    print('Resetting simulation')
    if(self.steps_since_reload>50000):
      self.load_default_project()
    self._initializeSimulation(ctypes.c_int(0))
    self.lastAction = np.zeros(5)
    self.storeAction(np.zeros(self.get_act_dim()))

    # Do some steps with zero action
    action = np.zeros(self.get_act_dim())
    self.storeAction(action)
    #for i in range(0, 100):
    #  self._advanceSingleTimestep()

    print('reset done')

    return self.maskObservation(self.extractObservation())

  def get_obs_dim(self):
    #return 23
    return 2

  def get_act_dim(self):
    #return 5
    return 2

  def get_act_high(self):
    gearbox_ratio = 97
    generator_torque = 47402.91
    return [generator_torque*gearbox_ratio, 90]

  # TODO get actual values for this
  def get_act_low(self):
    #return [0, 0, 0, 0, 0]
    return [0,0]

  def get_act_max_grad(self):
    timestep = 0.1
    gearbox_ratio = 97
    torque_step = 15000
    pitch_step = 8

    return [torque_step*gearbox_ratio*timestep, pitch_step*timestep]

  def get_obs_labels(self):
    return {
      0: 'rotational speed [rad/s]',
      1: 'power [kW]',
      2: 'HH wind velocity [m/s]',
      3: 'yaw angle [deg]',
      4: 'pitch blade 1 [deg]',
      5: 'pitch blade 2 [deg]',
      6: 'pitch blade 3 [deg]',
      7: 'tower top bending local x [Nm]',
      8: 'tower top bending local y [Nm]',
      9: 'tower top bending local z [Nm]',
      10: 'oop bending blade 1 [Nm]',
      11: 'oop bending blade 2 [Nm]',
      12: 'oop bending blade 3 [Nm]',
      13: 'ip bending blade 1 [Nm]',
      14: 'ip bending blade 2 [Nm]',
      15: 'ip bending blade 3 [Nm]',
      16: 'oop tip deflection blade 1 [m]',
      17: 'oop tip deflection blade 2 [m]',
      18: 'oop tip deflection blade 3 [m]',
      19: 'ip tip deflection blade 1 [m]',
      20: 'ip tip deflection blade 2 [m]',
      21: 'ip tip deflection blade 3 [m]',
      22: 'current time [s]'
    }

  def get_act_labels(self):
    return {
      0: 'generator torque [Nm]',
      1: 'collective pitch [deg]',
      #1: 'yaw angle [deg]',
      #2: 'pitch blade 1 [deg]',
      #3: 'pitch blade 2 [deg]',
      #4: 'pitch blade 3 [deg]'
    }

  def calc_reward(self, observation, action, death):
    if(death):
      death_penalty = 0.5 if observation[0] > 0 else 3
    else:
      death_penalty = 0

    rated_power = 3500
    rated_speed = 0.8
    #return -np.abs(observation[1]-rated_power) - 1e3*(np.abs(observation[16]) + np.abs(observation[17]) + np.abs(observation[18]))
    return np.clip(1-np.abs((observation[1]-rated_power)/rated_power)-death_penalty, -4, 4)
    #return np.clip(observation[1], 0, None) - 1e4*(np.abs(observation[16]) + np.abs(observation[17]) + np.abs(observation[18]))
    #return np.clip(5
    #  - np.abs((observation[1]-rated_power)/rated_power)
    #  - 5e-2*(np.abs(observation[16]) + np.abs(observation[17]) + np.abs(observation[18])), -10, 10)
    #return np.clip(1-np.abs((observation[0]-rated_speed)/rated_speed)-death_penalty, -4, 4)

  def calc_death(self, observation):
    # If there are nan values, reload completely
    self.steps_since_reload += 100000

    if(np.any(np.isnan(observation))):
      return True

    observation = np.nan_to_num(observation)

    # 63 is the rotor size, so if anything bends further than that, it's broken off.
    broken_state = 20
    max_rotorspeed = 3
    min_rotorspeed = -0.05
    max_power = 10000
    return np.abs(observation[16]) > broken_state or \
           np.abs(observation[17]) > broken_state or \
           np.abs(observation[18]) > broken_state or \
           observation[0] > max_rotorspeed or \
           observation[0] < min_rotorspeed or \
           observation[1] > max_power

  def padAction(self, action):
    action = [action[0], 0, action[1], action[1], action[1]]
    return action

  def storeAction(self, action):
    # Copy action to control vars
    action = np.clip(action, self.get_act_low(), self.get_act_high())
    action = np.nan_to_num(self.padAction(action))

    in_data = (ctypes.c_double * 5)(*action)
    self._setControlVars(in_data)

    self.lastAction = action

  def extractObservation(self, remove_nan=True):
    # 23 values are hardcoded in the library
    out_data = (ctypes.c_double * 23)()
    self._getControlVars(out_data)
    observation = [out_data[i] for i in range(0, 23)]

    if(remove_nan):
      observation = np.nan_to_num(observation)

    return observation

  def maskObservation(self, obs):
    return np.array(obs[0:2])

  def step(self, action):
    self.steps_since_reload += 1

    self.storeAction(action)
    self._advanceSingleTimestep()

    observation = self.extractObservation(False)

    death = self.calc_death(observation)
    observation = np.nan_to_num(observation)
    reward = self.calc_reward(observation, action, death)
    observation = self.maskObservation(observation)

    return observation, reward, death

  def render(self):
    pass

  def close(self):
    del self._qbladeLib

  def storeProject(self, filename):
    x = ctypes.c_char_p(bytes(filename, 'utf-8'))
    self._storeProject(x)


import numpy as np
import cv2
import os
import torch

import binary_image

def find_and_draw_contour_of_towel_from_binary(binary_TowelOnly, verbose=0):
    # Find contours
    im2, ctrs_TowelOnly, hier = cv2.findContours(binary_TowelOnly.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Sort contours (from left to right and top to bottom)
    sorted_ctrs_TowelOnly = sorted(ctrs_TowelOnly, key=lambda ctr: cv2.boundingRect(ctr)[0])
#     print('There is/are ' + str(len(sorted_ctrs_TowelOnly)) + ' contour(s) in Towel only.')

    # Find the bounding box of the contour closest to the top left corner
    # which has no size 1x1
    i, w, h = 0, 1, 1
    while i<len(sorted_ctrs_TowelOnly) and (w<=10 or h<=10):
        ctr = sorted_ctrs_TowelOnly[i]
        x, y, w, h = cv2.boundingRect(ctr) # Get bounding box
        if verbose==1:
            print("(u,v) of upper-left corner of the box = (" + str(x) + ", " + str(y) + ")")
            print("width and height of the box :", w, h)
        i+=1

    # Draw contours
    if verbose==1:
        # Draw the 0th contour:
        cv2.drawContours(img, [cnt], 0, (0,255,0), 3)

        # Draw all contours
    #     cv2.drawContours(img,ctrs_TowelOnly,-1,(0,0,255),1)
        cv2.imshow('image',img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    return [ctr] # list of a single element

def find_and_draw_contour_of_towel(input_png_name, verbose=0):
    # Binary image
    binary_TowelOnly = binary_image.binary_img_from_towel_igm_name(input_png_name, verbose)

    return find_and_draw_contour_of_towel_from_binary(binary_TowelOnly, verbose)

if __name__=='__main__':
    find_and_draw_contour_of_towel(input_png_name='RendersTowelWall11/Group.003/17.png', verbose=0)

def convert_contour_to_uv(ctrs_TowelOnly):
    """CAVEAT: convert_contour_to_uv only returns some uv pixels.
    The missing ones correspond to straight lines connecting the reported uv pixels"""
    xcnts = np.vstack((x.reshape(-1,2) for x in ctrs_TowelOnly[0]))
    u = xcnts[:,0]
    v = xcnts[:,1]
    return u, v

def convert_contour_to_uv_from_img_name(input_png_name, verbose=0):
    """CAVEAT: convert_contour_to_uv_from_img_name only returns some uv pixels.
    The missing ones correspond to straight lines connecting the reported uv pixels"""
    ctrs_TowelOnly = find_and_draw_contour_of_towel(input_png_name, verbose)
    return convert_contour_to_uv(ctrs_TowelOnly)

def convert_contour_to_uv_from_binary(binary_TowelOnly, verbose=0):
    """CAVEAT: convert_contour_to_uv_from_binary only returns some uv pixels.
    The missing ones correspond to straight lines connecting the reported uv pixels"""
    ctrs_TowelOnly = find_and_draw_contour_of_towel_from_binary(binary_TowelOnly, verbose)
    return convert_contour_to_uv(ctrs_TowelOnly)

def convert_contour_to_uv_from_img_name_slower(input_png_name, verbose=0):
    """CAVEAT: convert_contour_to_uv_from_img_name_slower only returns some uv pixels.
    The missing ones correspond to straight lines connecting the reported uv pixels"""
    ctrs_TowelOnly = find_and_draw_contour_of_towel(input_png_name, verbose)
    u=[]
    v=[]
    for i in range(len(ctrs_TowelOnly[0])):
        u.append(ctrs_TowelOnly[0][i][0][0])
    for i in range(len(ctrs_TowelOnly[0])):
        v.append(ctrs_TowelOnly[0][i][0][1])
    return u, v

if __name__=='__main__':
    import matplotlib.pyplot as plt
    import functions_plot
    sequence_name = 'TowelWall'
    dataset_number = '11'
    group_number = '003'
    animation_frame = '17'
#     animation_frame = '1'
    submesh_num_vertices_horizontal = 52
    submesh_num_vertices_vertical = 103
    verbose=0

    input_png_name = os.path.join('Renders' + sequence_name + dataset_number, 'Group.'+ group_number, animation_frame + '.png')
    u, v = convert_contour_to_uv_from_img_name(input_png_name=input_png_name, verbose=verbose)

    # Plot uv of contour without straight lines on RGB
    fig=functions_plot.plot_RGB_and_landmarks(u_visible=u, v_visible=v,
                                          sequence_name=sequence_name, dataset_number=dataset_number,
                                          group_number=group_number, animation_frame=animation_frame,
                                         marker_size=50/submesh_num_vertices_vertical)
    plt.show()

# Access all pixels from contour, without omitting the ones which describe straight lines
def append_missing_new_value(w, i, l):
    """ update w (u or v) adding the missing points between w[i] and w[i+1].
    l = len of the original w before undergoing any updates at all"""
    sign = 1 if w[(i+1)%l]>w[i%l] else -1
    for k in range(sign, w[(i+1)%l]-w[i%l], sign):
        w=np.append(w, w[i]+k)
    return w

def append_missing_copied_value(w, i, l, w_complementary):
    """ - update w (u or v) adding the missing points between w[i] and w[i+1].
    - l = len of the original w before undergoing any updates at all.
    - w_complementary = u if w is v and v if w is u.
    This is used to compute the number of copies to append to w. """
    n_copies = abs(w_complementary[(i+1)%l]-w_complementary[i%l])-1 # number of copies to append
    w = np.append(w, w[i]*np.ones((n_copies,), dtype=int))
    return w

def full_list_of_contour_pixels(u, v):
    """ This assumes the contour pixels are ordered but the output ones are not,
    since the new ones are appended at the end """
    l = len(u)
    for i in range(l):
        if abs(u[i%l]-u[(i+1)%l])>1 or abs(v[i%l]-v[(i+1)%l])>1:
            if abs(u[i%l]-u[(i+1)%l])==abs(v[i%l]-v[(i+1)%l]): # append diagonal
                u = append_missing_new_value(u, i, l)
                v = append_missing_new_value(v, i, l)
            elif u[i%l]-u[(i+1)%l]==0: # append vertical line
                u = append_missing_copied_value(u, i, l, v)
                v = append_missing_new_value(v, i, l)
            elif v[i%l]-v[(i+1)%l]==0: # append horizontal line
                u = append_missing_new_value(u, i, l)
                v = append_missing_copied_value(v, i, l, u)
    return u, v

if __name__=='__main__':
    u, v = full_list_of_contour_pixels(u, v)

    # Plot uv of full contour on RGB
    fig=functions_plot.plot_RGB_and_landmarks(u_visible=u, v_visible=v,
                                          sequence_name=sequence_name, dataset_number=dataset_number,
                                          group_number=group_number, animation_frame=animation_frame,
                                         marker_size=50/submesh_num_vertices_vertical)
    plt.show()

# Putting it all together
def full_list_of_contour_pixels_from_towel_imgname(input_png_name, verbose=0):
    u, v = convert_contour_to_uv_from_img_name(input_png_name, verbose)
    u, v = full_list_of_contour_pixels(u, v)
    return u, v

if __name__=='__main__':
    u, v = full_list_of_contour_pixels_from_towel_imgname(input_png_name, verbose)

    # Plot uv of full contour on RGB
    fig=functions_plot.plot_RGB_and_landmarks(u_visible=u, v_visible=v,
                                          sequence_name=sequence_name, dataset_number=dataset_number,
                                          group_number=group_number, animation_frame=animation_frame,
                                         marker_size=50/submesh_num_vertices_vertical)
    plt.show()

def full_list_of_contour_pixels_from_binary(binary_TowelOnly, verbose=0):
    u, v = convert_contour_to_uv_from_binary(binary_TowelOnly, verbose)
    if verbose==1:
        print("len(u):", len(u))
    u, v = full_list_of_contour_pixels(u, v)
    return u, v

if __name__=='__main__':
    binary_TowelOnly = binary_image.binary_img_from_towel_igm_name(input_png_name, verbose)

    u, v = full_list_of_contour_pixels_from_binary(binary_TowelOnly, verbose=0)

    # Plot uv of full contour on RGB
    fig=functions_plot.plot_RGB_and_landmarks(u_visible=u, v_visible=v,
                                          sequence_name=sequence_name, dataset_number=dataset_number,
                                          group_number=group_number, animation_frame=animation_frame,
                                         marker_size=50/submesh_num_vertices_vertical,
                                              title='full_list_of_contour_pixels_from_binary')
    plt.show()

def full_tensor_of_contour_pixels_from_binary(binary_TowelOnly, device='cpu', verbose=0, numpy_or_tensor=1, dtype=1):
    """ Find in the binary image named binary_TowelOnly the contour of the region of pixels occupied by the towel.
    If numpy_or_tensor=0, it returns a numpy array of shape Nx2, where the 1st column corresponds to u and 2nd to v.
    If numpy_or_tensor=1, it returns a tensor with the same properties instead.

    dtype==0 -->float
    dtype==1 -->double
    """
    u, v =full_list_of_contour_pixels_from_binary(binary_TowelOnly, verbose)

    if numpy_or_tensor==1:
        if dtype==0:
            return torch.from_numpy(np.concatenate((np.reshape(u, (-1, 1)),np.reshape(v, (-1, 1))), axis=1)).to(device).float().view(-1, 2)
        else:
            return torch.from_numpy(np.concatenate((np.reshape(u, (-1, 1)),np.reshape(v, (-1, 1))), axis=1)).to(device).double().view(-1, 2)

if __name__=='__main__':
    binary_TowelOnly = binary_image.binary_img_from_towel_igm_name(input_png_name, verbose)
    print(full_tensor_of_contour_pixels_from_binary(binary_TowelOnly, verbose=0, numpy_or_tensor=1))


from typing import Literal

import numpy as np

SPACINGS = Literal['equal', 'sine', 'cosine', 'neg_sine']

def unit_spacing(
    n_points: int,
    type_: SPACINGS,
) -> np.ndarray:
    """Spacing functions to create sequence of distributed points from zero to
    one.

    Parameters
    ----------
    n_points : int
        Number of points.
    type_ : Literal['equal', 'sine', 'cosine', 'neg_sine']
        Spacing type.

    Returns
    -------
    np.ndarray

    """
    spacings = dict(
        equal=lambda x: x,
        sine=lambda x: 1 - np.sin((1 + x) * np.pi / 2),
        cosine=lambda x: np.cos((1 + x) * np.pi)/2 + 1 / 2,
        neg_sine=lambda x: np.sin(x * np.pi / 2),
    )
    return spacings[type_](np.linspace(0, 1, n_points))

def spacing_like(
    array: np.array,
    n_points: int,
    type_: SPACINGS,
) -> np.ndarray:
    unit = unit_spacing(n_points, type_)
    return unit + array.min() * (array.max() - array.min())


from ultralytics import YOLO

# model = YOLO("../model/best.pt") # depen on pwd "WATCHOUT"
model = YOLO('best.pt')
results = model.predict(show=False, source= '../video_test/oto.mp4', save=True)
print(results)

# results = model.predict(show=True, source="0")
# print(results)

#save video after detect
#yolo task=detect mode=predict model=<path to weight file> conf=0.25 source=<path to source image or  video> save=True


# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, division, unicode_literals

import numpy as np
from numpy.lib.stride_tricks import as_strided
from scipy.stats import stats, rankdata

from measure_noise.utils import plot
from mo_dots import Data, coalesce
from mo_logs import Except

SHOW_CHARTS = False

THRESHOLD = 4
P_THRESHOLD = pow(10, -THRESHOLD)
MIN_POINTS = 6
MAX_POINTS = 50
TOP_EDGES = 0.05  # NUMBER OF POINTS TO INVESTIGATE EDGES (PERCENT)
JITTER = 20  # NUMBER OF SAMPLES (+/-) TO LOOK FOR BETTER EDGES

weight_scale = 5
weight_length = 30
forward = np.exp(-np.arange(weight_length) / weight_scale) / weight_scale
median_weight = np.array(list(forward[::-1]) + list(forward))
weight_radius = len(median_weight) // 2

SHOW_CHARTS and plot(median_weight, title="WEIGHT")

PERFHERDER_THRESHOLD_TYPE_ABS = 1
DEFAULT_THRESHOLD = 0.03

def find_segments(values, diff_type, diff_threshold):
    values = list(values)
    if len(values) == 0:
        return (0,), (0,)
    diff_threshold = coalesce(diff_threshold, DEFAULT_THRESHOLD)

    values = logs = np.array(values)
    if np.all(values > 0):
        logs = np.log(values)
    ranks = rankdata(values)

    SHOW_CHARTS and plot(ranks/len(values), title="RANKS")
    mwus = sliding_MWU(values)
    edge_detection = -np.log10(mwus[:, 1])
    # edge_detection = np.convolve(percentiles, edge_wavelet, mode="valid")
    SHOW_CHARTS and plot(edge_detection, title="EDGES -log10(p_value)")
    top_edges = np.argsort(-edge_detection)
    top_edges = filter_nearby_edges(top_edges[edge_detection[top_edges] > THRESHOLD / 3])

    # SORT THE EDGE DETECTION
    segments = np.array([0, len(values)] + list(top_edges))
    segments = np.sort(segments)
    diffs = np.zeros(len(segments))

    # CAN WE DO BETTER?
    for i, _ in enumerate(segments[:-2]):
        s, m, e = segments[i], segments[i + 1], segments[i + 2]
        m_score, t_score, best_mid = jitter_MWU(logs, s, m, e)
        if m_score.pvalue > P_THRESHOLD or s == best_mid or e == best_mid:
            # NO EVIDENCE OF DIFFERENCE, COLLAPSE SEGMENT
            segments[i + 1] = s
            continue
        if diff_type == PERFHERDER_THRESHOLD_TYPE_ABS:
            diff_percent = np.abs(
                np.median(values[s:best_mid]) - np.median(values[best_mid:e])
            )
            if diff_percent < diff_threshold:
                # DIFFERENCE IS TOO SMALL
                segments[i + 1] = s
                continue
        diff_percent = np.abs(
            np.median(values[best_mid:e]) / np.median(values[s:best_mid]) - 1
        )

        try:
            too_small = diff_percent < diff_threshold / 100
        except Exception as cause:
            raise cause

        if too_small:
            # DIFFERENCE IS TOO SMALL
            segments[i + 1] = segments[i]
            continue

        # LOOKS GOOD
        segments[i + 1] = best_mid
        diffs[i + 1] = diff_percent

    # REMOVE ZERO-LENGTH SEGMENTS
    non_zero_segments = segments[:-1] != segments[1:]
    segments = tuple([0] + list(segments[1:][non_zero_segments]))
    diffs = tuple([0] + list(diffs[1:][non_zero_segments]))
    return segments, diffs

def filter_nearby_edges(edges):
    if len(edges) == 0:
        return edges
    filter_edges = edges[:1]
    for e in edges[1:]:
        if np.any((filter_edges - MIN_POINTS <= e) & (e <= filter_edges + MIN_POINTS)):
            continue
        filter_edges = np.append(filter_edges, [e])
    return filter_edges

def cumvar(values):
    m = np.arange(len(values))
    count = m + 1
    cummean = np.cumsum(values) / count
    cumvar = ((values - cummean) ** 2) / m
    return cumvar

def cumSS(values):
    """
    RETURN CUMULATIVE SUM-OF-SQUARES
    :param values:
    """
    m = np.arange(len(values))
    count = m + 1
    cummean = np.cumsum(values) / count
    return (values - cummean) ** 2

no_good_edge = Data(pvalue=1)

def jitter_MWU(values, start, mid, end):
    """
    RETURN A BETTER MIDPOINT< ACCOUNTING FOR t-test RESULTS
    """

    # ADD SOME CONSTRAINTS TO THE RANGE OF VALUES TESTED
    m_start = min(mid, max(start + MIN_POINTS, mid - JITTER))
    m_end = max(mid, min(mid + JITTER, end - MIN_POINTS))
    if m_start == m_end:
        return no_good_edge, no_good_edge, mid
    mids = np.array(range(m_start, m_end))

    # MWU SCORES
    try:
        m_score = np.array(
            [
                stats.mannwhitneyu(
                    values[max(start, m - MAX_POINTS) : m],
                    values[m : min(end, m + MAX_POINTS)],
                    use_continuity=True,
                    alternative="two-sided",
                )
                for m in mids
            ]
        )

        t_score = np.array(
            [
                stats.ttest_ind(
                    values[max(start, m - MAX_POINTS) : m],
                    values[m : min(end, m + MAX_POINTS)],
                    equal_var=False,
                )
                for m in mids
            ]
        )

    except Exception as e:
        e = Except.wrap(e)
        if "All numbers are identical" in e:
            return no_good_edge, no_good_edge, mids[0]
        raise e

    # TOTAL SUM-OF-SQUARES
    # DO NOT KNOW WHAT THIS WAS DOING
    # if m_start - start == 0:
    #     # WE CAN NOT OFFSET BY ONE, SO WE ADD A DUMMY VALUE
    #     v_prefix = np.array([np.nan] + list(not_right(cumSS(values[start:m_end]), 1)))
    # else:
    #     # OFFSET BY ONE, WE WANT cumSS OF ALL **PREVIOUS** VALUES
    #     v_prefix = not_right(
    #         not_left(cumSS(values[start:m_end]), m_start - start - 1), 1
    #     )
    # v_suffix = not_right(cumSS(values[m_start:end][::-1])[::-1], end - m_end)
    # v_score = v_prefix + v_suffix
    # pvalue = np.sqrt(m_score[:, 1] * v_score)  # GOEMEAN OF SCORES

    # PICK LOWEST
    pvalue = np.sqrt(m_score[:, 1]*t_score[:,1])
    best = np.argmin(pvalue)

    return Data(pvalue=m_score[best, 1]), Data(pvalue=t_score[best, 1]), mids[best]

def sliding_MWU(values):
    """
    RETURN
    :param values:
    :return:
    """
    # ADD MEDIAN TO EITHER SIDE OF values
    prefix = [np.median(values[: i + weight_radius]) for i in range(weight_radius)]
    suffix = [
        np.median(values[-i - weight_radius:])
        for i in reversed(range(weight_radius))
    ]
    combined = np.array(prefix + list(values) + suffix)
    b = combined.itemsize
    window = as_strided(
        combined, shape=(len(values), weight_radius * 2), strides=(b, b)
    )

    med = (len(median_weight) + 1) / 2
    try:
        m_score = np.array(
            [
                stats.mannwhitneyu(
                    w[:weight_radius],
                    w[-weight_radius:],
                    use_continuity=True,
                    alternative="two-sided",
                )
                for v in window
                for r in [rankdata(v)]
                for w in [(r - med) * median_weight]
            ]
        )

        return m_score
    except Exception as cause:
        cause = Except.wrap(cause)
        if "All numbers are identical" in cause:
            return np.ones((window.shape[0], 2))
        raise cause


'''
-08/09/2021
-ImageCraft, a program made by Sebastian Jimenez
-This script is responsible for running the custom GUI for ImageCraft
'''

# Imports
from gooey import Gooey, GooeyParser
import os

# GUI configuration of tabs, size , name, ect..
@Gooey(program_name='IMAGE CRAFT', default_size=(700, 650),
       program_description='A program designed to turn digital images into mosaics made of minecraft blocks.',
       menu=[{
           'name': 'File',
           'items': [{
               'type': 'AboutDialog',
               'menuTitle': 'About',
               'name': 'Image Craft (Beta)',
               'description': '2021',
               'website': 'https://potassium3919.itch.io/',
               'developer': 'Sebastian Jimenez',

           }]
       }, {
           'name': 'Help',
           'items': [{
               'type': 'Link',
               'menuTitle': 'Source Code',
               'url': 'https://github.com/sjimenez100/ImageCraft'
           }]}])

# contains attributes that are refined versions of the raw GUI inputs
class ImageGUI:

    def __init__(self):
        self.host_image_path = None
        self.keywords = None
        self.threshold = None
        self.resolution_divider = None
        self.show_image = None
        self.fill_trans = None
        self.output_directory = None

    def start_get_and_clean(self):
        parser = GooeyParser()

        parser.add_argument('host_image_path',
                            metavar='Host Image',
                            widget='FileChooser', gooey_options={
                'validator': {
                    'test': 'str(user_input).endswith(".png") or str(user_input).endswith(".jpg")',
                    'message': 'Only image formats: (.png) or (.jpg) will be accepted'}},
                            help='Enter path of the image to process\n'
                                 r'Example: "C:\Users\user\Desktop\image.png"')

        parser.add_argument('-keywords',
                            metavar='Keywords (Recommended)',
                            help='Enter keywords separated by spaces to filter search\n'
                                 'Example: "concrete wool plank diamond blue"')

        parser.add_argument('-threshold',
                            metavar='Inverse Threshold', widget='Slider',
                            help='Enter an integer to adjust inverse threshold', default=15,
                            gooey_options={
                                'max': 150})

        parser.add_argument('-resolution_divider',
                            metavar='Resolution Factor', widget='Slider',
                            help='Enter an integer to adjust resolution (pixels per block)', default=8,
                            gooey_options={
                                'min': 1,
                                'max': 16})

        parser.add_argument('-show_image',
                            metavar='Display Image', widget='CheckBox',
                            help='Toggle whether to display image when process is complete',
                            action='store_false', default=True)

        parser.add_argument('-fill_trans',
                            metavar='Fill Transparency', widget='CheckBox',
                            help='Toggle whether to fill transparent pixels', action='store_true', default=False)

        parser.add_argument('-output_directory',
                            metavar='Output Location', widget='DirChooser',
                            default=rf'{os.path.join(os.getcwd(), "mosaics")}',
                            help='Enter path to output directory')

        inputs = parser.parse_args()

        self.threshold = int(inputs.threshold)
        self.fill_trans = bool(inputs.fill_trans)

        if str(inputs.keywords).isspace() or inputs.keywords is None:
            self.keywords = []
        else:
            self.keywords = list(str(inputs.keywords).split())

        self.host_image_path = inputs.host_image_path
        self.resolution_divider = int(inputs.resolution_divider)
        self.output_directory = inputs.output_directory
        self.show_image = not bool(inputs.show_image)


# 암호 만들기

import sys
from itertools import combinations

l, c = map(int, sys.stdin.readline().split())
crypto = list(sys.stdin.readline().strip().split(" "))
crypto.sort()
con = 0  # 자음 개수
vow = 0  # 모음 개수

if __name__ == "__main__":
    for com in combinations(crypto, l):
        for c in com:
            if c == "a" or c == "e" or c == "i" or c == "o" or c == "u":
                vow += 1
            else:
                con += 1
        if vow >= 1 and con >= 2:
            print("".join(com))

        con = 0
        vow = 0


from tree.Tree import Node

class BinaryTree:

    def __init__(self, inorder, postorder):
        n = len(inorder)
        inorder_map = {num: i for i, num in enumerate(inorder)}
        self.root = self._build(inorder, postorder, inorder_map, 0, n - 1, 0, n - 1)
        pass

    def _build(self, inorder, postorder, inorder_map, in_start, in_end, post_start, post_end):
        if in_start > in_end:
            return None
        node = Node(postorder[post_end])
        i = inorder_map[postorder[post_end]]
        right_size = in_end - (i + 1)
        node.left = self._build(inorder, postorder, inorder_map, in_start, i - 1, post_start,
                                post_end - 1 - right_size - 1)
        node.right = self._build(inorder, postorder, inorder_map, i + 1, in_end, post_end - 1 - right_size,
                                 post_end - 1)
        return node

    def inorder(self):
        result = []
        self._inorder(self.root, result)
        return result

    def _inorder(self, node, result):
        if node:
            self._inorder(node.left, result)
            result.append(node.val)
            self._inorder(node.right, result)

    def postorder(self):
        result = []
        self._postorder(self.root, result)
        return result

    def _postorder(self, node, result):
        if node:
            self._postorder(node.left, result)
            self._postorder(node.right, result)
            result.append(node.val)

in_order = [40, 20, 50, 10, 60, 30]
post_order = [40, 50, 20, 60, 30, 10]

b = BinaryTree(in_order, post_order)
print(b.inorder())
print(b.postorder())


from fastapi import FastAPI, File, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware

from src.auth.routers.auth import router as auth_router
from src.auth.routers.user import router as user_router
from src.profiles.router import router as profile_router
from src.workspace.router import router as workspace_router
from src.folder.router import router as folder_router
from src.folder.router import router_without_workspace_id as folder_router_without_workspace_id
from src.abstract.router import router as abstract_router
from src.abstract.router import router_without_folder_id as abstract_router_without_router_id

import boto3
from src.config import YandexS3Config

app = FastAPI(title='Rec & Rem Backend')

origins = ["http://localhost:3000", 'https://localhost:8080']

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE", "PUT"],
    allow_headers=["Content-Type", "Set-Cookie"]
)

app.include_router(abstract_router)
app.include_router(abstract_router_without_router_id)
app.include_router(folder_router)
app.include_router(folder_router_without_workspace_id)
app.include_router(workspace_router)
app.include_router(profile_router)
app.include_router(user_router)
app.include_router(auth_router)

@app.get('/')
def home():
    return {'status': 'Ok'}

session = boto3.session.Session()
s3 = session.client(
    service_name='s3',
    endpoint_url='https://storage.yandexcloud.net',
    aws_access_key_id=YandexS3Config.AWS_ACCESS_KEY_ID,
    aws_secret_access_key=YandexS3Config.AWS_SECRET_ACCESS_KEY,
    region_name='ru-central1'
)

@app.post('/file')
async def download_file(file: UploadFile = File()):
    s3.upload_fileobj(file.file, Bucket='rec-and-rem-test', Key=f'static/{file.filename}')
    return

@app.get('/file')
async def get_file():
    file = s3.get_object(Bucket='rec-and-rem-test', Key='static/globe.png')
    return StreamingResponse(file['Body'])


def solution(myString, pat):
    answer = 0
    newSt = ''
    for idx,k in enumerate(myString):
        if k =='A':
            newSt += 'B'
        else:
            newSt += 'A'

    if pat in newSt:
        return 1
    else:
        return 0

프로그래머스/unrated/181864. 문자열 바꿔서 찾기/문자열 바꿔서 찾기.py

문자열 바꿔서 찾기.py


from odoo.tests import common, tagged

@tagged("post_install", "-at_install")
class TestAnalyticUsability(common.SavepointCase):

    @classmethod
    def setUpClass(cls):
        super(TestAnalyticUsability, cls).setUpClass()
        cls.account = cls.env.ref('analytic.analytic_administratif')
        cls.line = cls.env['account.analytic.line'].create({
            'name': 'Test Line',
            'account_id': cls.account.id,
        })
        cls.partner = cls.env["res.partner"].create({
            "name": "Test Partner",
            "user_id": cls.env.ref("base.user_admin").id,
        })

    def test_analytic_usability(self):
        self.assertEqual(self.line.amount, 0)
        self.assertEqual(self.line.amount_type, 'revenue')
        self.line.write({
            'amount': -100,
        })
        self.assertEqual(self.line.amount_type, 'cost')
        self.line.write({
            'amount': 100,
        })
        self.assertEqual(self.line.amount_type, 'revenue')

    def test_analytic_account(self):
        self.assertFalse(self.account.partner_id)
        self.assertEqual(self.account.user_id, self.env.user)
        self.account.write({
            "partner_id": self.partner.id,
        })
        self.account._onchange_partner_id()
        self.assertEqual(self.account.user_id, self.partner.user_id)


def finder(files, queries):

	file_dict = {}

	result = []

	length = len(files)

	for i in range(length):

		parsed_file_path = files[i].split('/')

		file_name = parsed_file_path[len(parsed_file_path)-1]

		if file_name in file_dict:

			file_dict[file_name].add(i)

		else:

			file_dict[file_name] = set()
			file_dict[file_name].add(i)

	for query in queries:

		if query in file_dict:

			num_files = len(file_dict[query])

			while num_files > 0:

				result += [files[file_dict[query].pop()]]

				num_files -= 1

	return result

if __name__ == "__main__":
	files = [
		'/bin/foo',
		'/bin/bar',
		'/usr/bin/baz'
	]
	queries = [
		"foo",
		"qux",
		"baz"
	]
	print(finder(files, queries))


import os
import argparse

import tensorflow.compat.v1 as tf

from fedlearner.common.metric_collector import metric_collector
from fedlearner.trainer.cluster_server import ClusterServer
from fedlearner.trainer._global_context import global_context as _gctx

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='FedLearner Parameter Server.')
    parser.add_argument('address', type=str,
                        help='Listen address of the parameter server, ' \
                             'with format [IP]:[PORT]')
    args = parser.parse_args()

    _gctx.task = "ps"
    global_tags = {
        'task': _gctx.task,
        'task_index': str(_gctx.task_index),
        'node_name': os.environ.get('HOSTNAME', 'default_node_name'),
        'pod_name': os.environ.get('POD_NAME', 'default_pod_name'),
    }
    metric_collector.add_global_tags(global_tags)
    name_prefix = 'model.common.nn_vertical'
    metric_collector.emit_counter(f'{name_prefix}.start_count', 1)

    cluster_spec = tf.train.ClusterSpec({'ps': {0: args.address}})
    cluster_server = ClusterServer(cluster_spec, "ps")
    cluster_server.join()