import os

import torch

from typing import List, Dict
from .utils import logits_to_scores
from .motion import Motion

from structures.track_instances import TrackInstances

class RuntimeTracker:
    def __init__(self, det_score_thresh: float = 0.7, track_score_thresh: float = 0.6,
                 miss_tolerance: int = 5,
                 use_motion: bool = False, motion_min_length: int = 3, motion_max_length: int = 5,
                 visualize: bool = False, use_dab: bool = True):
        self.det_score_thresh = det_score_thresh
        self.track_score_thresh = track_score_thresh
        self.miss_tolerance = miss_tolerance
        self.max_obj_id = 0
        self.use_motion = use_motion
        self.visualize = visualize
        self.motion_min_length = motion_min_length
        self.motion_max_length = motion_max_length
        self.motions: Dict[Motion] = {}
        self.use_dab = use_dab

    def update(self, model_outputs: dict, tracks: List[TrackInstances]):
        assert len(tracks) == 1
        model_outputs["scores"] = logits_to_scores(model_outputs["pred_logits"])
        n_dets = len(model_outputs["det_query_embed"])

        if self.visualize:
            os.makedirs("./outputs/visualize_tmp/runtime_tracker/", exist_ok=True)
            visualize_ids = tracks[0].ids.cpu().tolist()

        # Update tracks.
        tracks[0].boxes = model_outputs["pred_bboxes"][0][n_dets:]
        tracks[0].logits = model_outputs["pred_logits"][0][n_dets:]
        tracks[0].output_embed = model_outputs["outputs"][0][n_dets:]
        tracks[0].scores = logits_to_scores(tracks[0].logits)
        for i in range(len(tracks[0])):
            if tracks[0].scores[i][tracks[0].labels[i]] < self.track_score_thresh:
                tracks[0].disappear_time[i] += 1
            else:
                if self.use_motion and tracks[0].disappear_time[i] > 0:
                    self.motions[tracks[0].ids[i].item()].clear()
                tracks[0].disappear_time[i] = 0
                if self.use_motion:
                    self.motions[tracks[0].ids[i].item()].add_box(tracks[0].boxes[i].cpu())
                    tracks[0].last_appear_boxes[i] = tracks[0].boxes[i]
            if tracks[0].disappear_time[i] >= self.miss_tolerance:
                tracks[0].ids[i] = -1

        # Add newborn targets.
        new_tracks = TrackInstances(hidden_dim=tracks[0].hidden_dim, num_classes=tracks[0].num_classes)
        new_tracks_idxes = torch.max(model_outputs["scores"][0][:n_dets], dim=-1).values >= self.det_score_thresh
        new_tracks.logits = model_outputs["pred_logits"][0][:n_dets][new_tracks_idxes]
        new_tracks.boxes = model_outputs["pred_bboxes"][0][:n_dets][new_tracks_idxes]
        new_tracks.ref_pts = model_outputs["last_ref_pts"][0][:n_dets][new_tracks_idxes]
        new_tracks.scores = model_outputs["scores"][0][:n_dets][new_tracks_idxes]
        new_tracks.output_embed = model_outputs["outputs"][0][:n_dets][new_tracks_idxes]
        # new_tracks.query_embed = model_outputs["aux_outputs"][-1]["queries"][0][:n_dets][new_tracks_idxes]
        if self.use_dab:
            new_tracks.query_embed = model_outputs["aux_outputs"][-1]["queries"][0][:n_dets][new_tracks_idxes]
        else:
            new_tracks.query_embed = torch.cat(
                (
                    model_outputs["det_query_embed"][new_tracks_idxes][:, :256],    # hack
                    model_outputs["aux_outputs"][-1]["queries"][0][:n_dets][new_tracks_idxes]
                ),
                dim=-1
            )
        new_tracks.disappear_time = torch.zeros((len(new_tracks.logits), ), dtype=torch.long)
        new_tracks.labels = torch.max(new_tracks.scores, dim=-1).indices

        # We do not use this post-precess motion module in our final version,
        # this will bring a slight improvement,
        # but makes un-elegant.
        if self.use_motion:
            new_tracks.last_appear_boxes = model_outputs["pred_bboxes"][0][:n_dets][new_tracks_idxes]
        ids = []
        for i in range(len(new_tracks)):
            ids.append(self.max_obj_id)
            self.max_obj_id += 1
        new_tracks.ids = torch.as_tensor(ids, dtype=torch.long)
        new_tracks = new_tracks.to(new_tracks.logits.device)
        for _ in range(len(new_tracks)):
            self.motions[new_tracks.ids[_].item()] = Motion(
                min_record_length=self.motion_min_length,
                max_record_length=self.motion_max_length
            )
            self.motions[new_tracks.ids[_].item()].add_box(new_tracks.boxes[_].cpu())

        if self.visualize:
            visualize_ids += ids
            torch.save(torch.as_tensor(visualize_ids),
                       "./outputs/visualize_tmp/runtime_tracker/ids.tensor")

        return tracks, [new_tracks]


# -*- coding: utf-8 -*-
"""
Created on Sun Jun 16 23:10:05 2019

@author: User
"""
import pandas as pd
import numpy as np
import newspaper
# to install newspaper for python3
# pip install newspaper3k
from newspaper import fulltext
from newspaper import Article

# getting some news articles from these 3 sites
cnn_paper = newspaper.build('http://cnn.com')
fox_paper = newspaper.build('http://fox.com')
reuter_paper = newspaper.build('http://reuters.com')

# Getting categories of the 3 news sites
for category in cnn_paper.category_urls():
        print(category)

for category in fox_paper.category_urls():
        print(category)

for category in reuter_paper.category_urls():
        print(category)

# focusing on U.S, url obtained from categories above
cnn_paper = newspaper.build('http://cnn.com/us')
fox_paper = newspaper.build('http://fox.com')
reuter_paper = newspaper.build('http://reuters.com')

# get text from the first 10 article of each source

news_df_columns = ['Site', 'url', 'news_title', 'news_text']
news_df = pd.DataFrame(columns=news_df_columns)
# process at most 10 articles from each source
max_article = 5

# load CNN article text
cnn_count = 0
for article in cnn_paper.articles:
    # article count ++
    cnn_count = cnn_count + 1

    # get article text
    a= Article(article.url)
    a.download()
    a.parse()

    print(article.url)

    # append to dataframe
    row = ["CNN", a.title, article.url, a.text]
    news_df.loc[len(news_df)] = row
    if(cnn_count > max_article):
        break

# load FOX article text
fox_count = 0
for article in fox_paper.articles:
    # article count ++
    fox_count = fox_count + 1

    # get article text
    a= Article(article.url)
    a.download()
    a.parse()

    # append to dataframe
    row = ["FOX", a.title, article.url, a.text]
    news_df.loc[len(news_df)] = row
    if(cnn_count > max_article):
        break


import datetime
import json
import os
import numpy as np
import torch
from PIL import Image
from matplotlib import pyplot as plt
from scipy.sparse import coo_matrix
from scipy.stats import multivariate_normal
from torch import nn
from torchvision.datasets import VisionDataset
from torchvision.transforms import ToTensor

from multiview_detector.utils.projection import *

class frameDataset(VisionDataset):
    def __init__(self, base, train=True, transform=ToTensor(), target_transform=ToTensor(),
                 reID=False, grid_reduce=4, img_reduce=4, train_ratio=0.9, force_download=True):
        # Totensor() Convert a PIL Image or numpy.ndarray to tensor. This transform does not support torchscript.
        super().__init__(base.root, transform=transform, target_transform=target_transform)

        map_sigma, map_kernel_size = 20 / grid_reduce, 20
        img_sigma, img_kernel_size = 20 / img_reduce, 20
        self.reID, self.grid_reduce, self.img_reduce = reID, grid_reduce, img_reduce

        self.base = base
        self.root, self.num_cam, self.num_frame = base.root, base.num_cam, base.num_frame
        self.img_shape, self.worldgrid_shape = base.img_shape, base.worldgrid_shape  # H,W; N_row,N_col
        self.reducedgrid_shape = list(map(lambda x: int(x / self.grid_reduce), self.worldgrid_shape))

        if train:
            frame_range = range(0, int(self.num_frame * train_ratio))  # 0.9
        else:
            frame_range = range(int(self.num_frame * train_ratio), self.num_frame)

        self.img_fpaths = self.base.get_image_fpaths(frame_range)
        self.map_gt = {}
        self.imgs_head_foot_gt = {}
        self.download(frame_range)

        self.gt_fpath = os.path.join(self.root, 'gt.txt')
        if not os.path.exists(self.gt_fpath) or force_download:
            self.prepare_gt()

        x, y = np.meshgrid(np.arange(-map_kernel_size, map_kernel_size + 1),
                           np.arange(-map_kernel_size, map_kernel_size + 1))

        pos = np.stack([x, y], axis=2)
        map_kernel = multivariate_normal.pdf(pos, [0, 0], np.identity(2) * map_sigma)
        map_kernel = map_kernel / map_kernel.max()
        kernel_size = map_kernel.shape[0]
        self.map_kernel = torch.zeros([1, 1, kernel_size, kernel_size], requires_grad=False)
        self.map_kernel[0, 0] = torch.from_numpy(map_kernel)

        x, y = np.meshgrid(np.arange(-img_kernel_size, img_kernel_size + 1),
                           np.arange(-img_kernel_size, img_kernel_size + 1))
        pos = np.stack([x, y], axis=2)
        img_kernel = multivariate_normal.pdf(pos, [0, 0], np.identity(2) * img_sigma)
        img_kernel = img_kernel / img_kernel.max()
        kernel_size = img_kernel.shape[0]
        self.img_kernel = torch.zeros([2, 2, kernel_size, kernel_size], requires_grad=False)
        self.img_kernel[0, 0] = torch.from_numpy(img_kernel)
        self.img_kernel[1, 1] = torch.from_numpy(img_kernel)
        pass

    def prepare_gt(self):
        og_gt = []
        for fname in sorted(os.listdir(os.path.join(self.root, 'annotations_positions'))):
            frame = int(fname.split('.')[0])
            with open(os.path.join(self.root, 'annotations_positions', fname)) as json_file:
                all_pedestrians = json.load(json_file)
            for single_pedestrian in all_pedestrians:
                def is_in_cam(cam):
                    return not (single_pedestrian['views'][cam]['xmin'] == -1 and
                                single_pedestrian['views'][cam]['xmax'] == -1 and
                                single_pedestrian['views'][cam]['ymin'] == -1 and
                                single_pedestrian['views'][cam]['ymax'] == -1)

                in_cam_range = sum(is_in_cam(cam) for cam in range(self.num_cam))
                if not in_cam_range:
                    continue
                grid_x, grid_y = self.base.get_worldgrid_from_pos(single_pedestrian['positionID'])
                og_gt.append(np.array([frame, grid_x, grid_y]))

        og_gt = np.stack(og_gt, axis=0)
        os.makedirs(os.path.dirname(self.gt_fpath), exist_ok=True)
        np.savetxt(self.gt_fpath, og_gt, '%d')

    def download(self, frame_range):
        # 每张图片中的每个人在每个相机下
        # 第一个for循环生成map_gt列表，包含1800帧图像，一个元素代表对应图像中每个人的位置
        # 第二个for循环生成imgs_head_foot列表，一个元素代表一帧图像中所有人在所有相机视角下head和foot位置
        for fname in sorted(os.listdir(os.path.join(self.root, 'annotations_positions'))):
            frame = int(fname.split('.')[0])
            if frame in frame_range:
                with open(os.path.join(self.root, 'annotations_positions', fname)) as json_file:
                    all_pedestrians = json.load(json_file)
                i_s, j_s, v_s = [], [], []  # world grid coord
                head_row_cam_s, head_col_cam_s = [[] for _ in range(self.num_cam)], \
                                                 [[] for _ in range(self.num_cam)]
                foot_row_cam_s, foot_col_cam_s, v_cam_s = [[] for _ in range(self.num_cam)], \
                                                          [[] for _ in range(self.num_cam)], \
                                                          [[] for _ in range(self.num_cam)]

                for single_pedestrian in all_pedestrians:
                    x, y = self.base.get_worldgrid_from_pos(single_pedestrian['positionID'])
                    if self.base.indexing == 'xy':
                        i_s.append(int(y / self.grid_reduce))
                        j_s.append(int(x / self.grid_reduce))
                    else:
                        i_s.append(int(x / self.grid_reduce))
                        j_s.append(int(y / self.grid_reduce))
                    v_s.append(single_pedestrian['personID'] + 1 if self.reID else 1)
                    for cam in range(self.num_cam):
                        x = max(min(int((single_pedestrian['views'][cam]['xmin'] +
                                         single_pedestrian['views'][cam]['xmax']) / 2), self.img_shape[1] - 1), 0)
                        y_head = max(single_pedestrian['views'][cam]['ymin'], 0)
                        y_foot = min(single_pedestrian['views'][cam]['ymax'], self.img_shape[0] - 1)
                        if x > 0 and y > 0:
                            head_row_cam_s[cam].append(y_head)
                            head_col_cam_s[cam].append(x)
                            foot_row_cam_s[cam].append(y_foot)
                            foot_col_cam_s[cam].append(x)
                            v_cam_s[cam].append(single_pedestrian['personID'] + 1 if self.reID else 1)
                occupancy_map = coo_matrix((v_s, (i_s, j_s)), shape=self.reducedgrid_shape)  # 120, 360
                self.map_gt[frame] = occupancy_map
                self.imgs_head_foot_gt[frame] = {}
                for cam in range(self.num_cam):
                    img_gt_head = coo_matrix((v_cam_s[cam], (head_row_cam_s[cam], head_col_cam_s[cam])),
                                             shape=self.img_shape)
                    img_gt_foot = coo_matrix((v_cam_s[cam], (foot_row_cam_s[cam], foot_col_cam_s[cam])),
                                             shape=self.img_shape)
                    self.imgs_head_foot_gt[frame][cam] = [img_gt_head, img_gt_foot]

    def __getitem__(self, index):  ####
        frame = list(self.map_gt.keys())[index]
        imgs = []
        for cam in range(self.num_cam):
            fpath = self.img_fpaths[cam][frame]
            img = Image.open(fpath).convert('RGB')
            if self.transform is not None:
                img = self.transform(img)
            imgs.append(img)
        imgs = torch.stack(imgs)
        map_gt = self.map_gt[frame].toarray()
        if self.reID:
            map_gt = (map_gt > 0).int()
        if self.target_transform is not None:
            map_gt = self.target_transform(map_gt)
        imgs_gt = []
        for cam in range(self.num_cam):
            img_gt_head = self.imgs_head_foot_gt[frame][cam][0].toarray()
            img_gt_foot = self.imgs_head_foot_gt[frame][cam][1].toarray()
            img_gt = np.stack([img_gt_head, img_gt_foot], axis=2)
            if self.reID:
                img_gt = (img_gt > 0).int()
            if self.target_transform is not None:
                img_gt = self.target_transform(img_gt)
            imgs_gt.append(img_gt.float())
        imgs_gt = torch.stack(imgs_gt)
        return imgs, map_gt.float(), imgs_gt, frame

    def __len__(self):
        return len(self.map_gt.keys())

def test():
    from datasets.W_M.Wildtrack import Wildtrack
    # from datasets.MultiviewX import MultiviewX
    from multiview_detector.utils.projection import get_worldcoord_from_imagecoord
    dataset = frameDataset(Wildtrack(os.path.expanduser('~/Data/Wildtrack')))
    import torch.nn.functional as F
    imgs, map_gt, imgs_gt, _ = dataset.__getitem__(0)

    print('map_gt shape', map_gt.shape)
    print('img_gt shape', imgs_gt[0].shape)
    print('sum of imgs-gt[0]', imgs_gt[0].sum().item())
    print('img max', imgs_gt[0].max())
    print('kernel shape==', dataset.map_kernel.shape)

    map_gt = F.conv2d(map_gt.detach().unsqueeze(0), dataset.map_kernel.float(),
                      padding=int((dataset.map_kernel.shape[-1] - 1) / 2))
    img_gt0 = F.adaptive_max_pool2d(imgs_gt[0][None], (270, 480))
    img_gt0 = F.conv2d(img_gt0, dataset.img_kernel.float(),
                       padding=int((dataset.img_kernel.shape[-1] - 1) / 2))
    print('img_gt0 shape', img_gt0.shape)
    # plt.imshow(map_gt.squeeze())
    # plt.show()
    plt.imshow(img_gt0[0][0].squeeze())
    plt.show()
    plt.imshow(img_gt0[0][1].squeeze())
    plt.show()
    print(datetime.datetime.now())

if __name__ == '__main__':
    test()


from django.urls import path
from django.conf import settings
from django.conf.urls.static import static

from . import views

app_name = 'index'
urlpatterns = [
    path('', views.index, name='index'),
    path('login/', views.login, name='login'),
    path('login/<path:next_page>', views.login, name='login'),
    path('make_login/<path:next_page>', views.make_login, name='make_login'),
    path('create_account', views.create_account, name='create_account'),
    path('create_account/<path:next_page>', views.create_account, name='create_account'),
    path('sign_up', views.sign_up, name='sign_up'),
    path('sign_up/<path:next_page>', views.sign_up, name='sign_up'),
    path('logout', views.logout, name='logout'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


# 피보나치 수는 0과 1로 시작한다. 0번째 피보나치 수는 0이고, 1번째 피보나치 수는 1이다. 그 다음 2번째 부터는 바로 앞 두 피보나치 수의 합이 된다.

# 이를 식으로 써보면 Fn = Fn-1 + Fn-2 (n ≥ 2)가 된다.

# n=17일때 까지 피보나치 수를 써보면 다음과 같다.

# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597

# n이 주어졌을 때, n번째 피보나치 수를 구하는 프로그램을 작성하시오.

def fib(n):
    if n<=1:
        return n
    return fib(n-1) + fib(n-2)

n = int(input())
print(fib(n))


# 2. Duplicated Products
# You are given a complex list of n products, each with a name, price,
# and weight. Find out how many duplicate products are present
# within the list. Duplicate products contain identical parameters for
# all fields in the list (i.e. name, price, and weight).
# Example:
# There are n = 5 products with attributes listed in three arrays,
# aligned by index.
# name = [ball, bat, glove, glove, glove]
# price = [2, 3, 1, 2, 1]
# weight = [2, 5, 1, 1, 1]
# A complete item description for item 0: (name[0], prices[0], 0:
# weight[0]) is (ball, 2, 2)
# Name
# Price Weight
# ball
# 2
# 2
# bat
# 3
# 5
# glove
# 1
# 1
# glove
# 2
# 1
# glove
# 1
# 1
# The first two items are unique.
# The two gloves at indices 2 and 4 are equal in all three attributes so
# there is 1 duplicate.
# The last glove at index 3 has a different price from the other two, so
# it is not a duplicate.
# There is 1 duplicate item in the original list.
#
# Function Description
# Complete the function numDuplicates in the editor below. The
# function must return an integer denoting the number of duplicates
# within the product list.
# numDuplicates has the following parameter(s):
# string name[n}. string array of size n, where names[i] denotes the
# name of the product at the index of i.
# int price[n): int array of size n, where prices[i] denotes the price of
# the product at the index of i.
# int weight[n]. int array of size n, where weights[i] denotes the
# weight of the product at the index of i.

def numDuplicates(name, price, weight):
    n = len(name)
    products = [(name[i], price[i], weight[i]) for i in range(n)]
    unique_products = set(products)
    return n - len(unique_products)

if __name__ == '__main__':
    result = numDuplicates(['ball', 'bat', 'glove', 'glove', 'glove'], [2, 3, 1, 2, 1], [2, 5, 1, 1, 1])
    print(result)


class Solution:
    def longestValidParentheses(self, s: str) -> int:
        ans, stack = 0, [-1]  # Store the index of each upper parenthesis we met
        for i, c in enumerate(s):
            if c == ')':
                stack.pop()
                if stack:  # There is valid upper parenthesis in stack
                    ans = max(ans, i - stack[-1])
                    continue
            stack.append(i)
        return ans


"""empty message

Revision ID: 960f30ca1caa
Revises:
Create Date: 2020-09-24 19:04:05.554749

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '960f30ca1caa'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('ej',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('nome', sa.String(length=255), nullable=False),
    sa.Column('imagem', sa.String(length=255), nullable=True),
    sa.Column('cnpj', sa.String(length=100), nullable=True),
    sa.Column('projetos_meta', sa.Integer(), nullable=True),
    sa.Column('faturamento_meta', sa.Integer(), nullable=True),
    sa.Column('projetos_atual', sa.Integer(), nullable=True),
    sa.Column('faturamento_atual', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('cnpj'),
    sa.UniqueConstraint('nome')
    )
    op.create_table('tarefa',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('titulo', sa.String(length=255), nullable=False),
    sa.Column('descricao', sa.Text(), nullable=False),
    sa.Column('icone', sa.String(length=255), nullable=True),
    sa.Column('prazo', sa.String(length=100), nullable=True),
    sa.Column('ehSolo', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('titulo')
    )
    op.create_table('usuario',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('nome', sa.Integer(), nullable=False),
    sa.Column('login', sa.String(length=255), nullable=True),
    sa.Column('senha', sa.String(length=255), nullable=False),
    sa.Column('urole', sa.String(length=50), server_default='user', nullable=False),
    sa.Column('email', sa.String(length=80), nullable=False),
    sa.Column('active', sa.Boolean(), server_default=sa.text('true'), nullable=True),
    sa.Column('foto_trainee', sa.String(length=120), nullable=True),
    sa.Column('ej_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['ej_id'], ['ej.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('email'),
    sa.UniqueConstraint('login')
    )
    op.create_table('tarefaTrainee',
    sa.Column('id_trainee', sa.Integer(), nullable=False),
    sa.Column('id_tarefa', sa.Integer(), nullable=False),
    sa.Column('atrasada', sa.Boolean(), nullable=True),
    sa.ForeignKeyConstraint(['id_tarefa'], ['tarefa.id'], ),
    sa.ForeignKeyConstraint(['id_trainee'], ['usuario.id'], ),
    sa.PrimaryKeyConstraint('id_trainee', 'id_tarefa')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('tarefaTrainee')
    op.drop_table('usuario')
    op.drop_table('tarefa')
    op.drop_table('ej')
    # ### end Alembic commands ###


#!/usr/bin/env python3

def main():
    # python dilinde diğer dillerdeki gibi "tip" değişken tanımlanmaz
    # bunun yerine değişkeni isimlendirip değeri = ile atayabiliriz. örn.
    # sayi = 128
    # cumle = "python programlama dili"
    # global değişken örneği için tüm fonksiyonların ( def ) dışında kalan bir alanda
    # genelde ismi BÜYÜK harfle yazılarak dosya içerisinde bir yere yazılabilir
    # örn. main() çağırdığımız kod bloğunun üzeri bunun için en iyi yer büyük harf kullanmanızı öneriyorum
    sayi = 128
    cumle = "python programlama dili örnekler."
    print(sayi)
    print(cumle)
    # burda global kullanarak aşağıdaki GENEL değişkenini çağırmayı deneyelim.
    # eğer global tanımını kullanmazsanız çalışmayacaktır
    # UnboundLocalError: local variable 'GENEL' referenced before assignment hatası verir
    # ve GENEL değişkeninin fonksiyon içindeki bir değişken olduğunu varsayar.
    global GENEL
    print(GENEL)
    # ardından değiştirmeyi deneyelim.
    GENEL = "Ben değiştim."
    print(GENEL)

GENEL = "Genel kullanım için tanımlanan değişken"

if __name__ == "__main__":
    # bu kod bloğu ise eğer pythonda main fonksiynu varsa misal yukardaki gibi
    # yorumlayıcıya hangi def ile başlayacağını gösteriyor isim illaki main olmak zorunda değil
    # ama genel kabul görmüş maindir alışkanlık edinmenizi öneririm
    # GNU/Linux Yada BSD kullanan arkadaşlar dosya başına mutlaka
    # #!/usr/bin/env python3 eklemelidir daha sonra dosyanın doğrudan çağrılıp çalıştırılması için chmod +x dosya.py
    main()


#!/usr/bin/env python3
import pandas as pd
import sys
import numpy as np

input_sea = 5                                           #This is the value that the user will select
elev = [[1,2,3], [4,5,6], [7,8,9]]                      # Arbitratry numbers to make a 3x3 dataframe as data input for determining sea level.
elev_df = pd.DataFrame(elev)      # This is the data fram generated based on elevation innput, will get this from Meike
#print(elev_df)

sea_lev_df = elev_df.apply(lambda x: x -input_sea)          # Makes a sea level dataframe by taking the input sea level set by the user and substracting from the elevation dataframe. In the following steps if values are <0 then the coordinate is below sea level and the value is set to 0, if the value is >0 the coordinate is above sea level and the value of the coordinate is set to 1.
#print(sea_lev_df)

land_level = []                                             #Makes an empty list to store the land level values
for x in range(sea_lev_df.shape[0]):                        # Itereate over rows of sea_lev_df
    for y in range(sea_lev_df.shape[1]):                    # Iterate over columns of sea_lev_df to identify the if and else statements
        if sea_lev_df.at[x,y] < 0:                          # If values are <0 then the coordinate is below sea level and the value is set to 0
            land_level.append(0)                            #Adds the value of the coordinate to the land_level list
        else:
            land_level.append(1)                            #Adds the value of the coordinate to the land_list
#print(land_level)

n = 3                                                        #number of colums we want in the land_level_matrix dataframe
land_level_matrix = [land_level[x:x +n] for x in range(0, len(land_level), n)]  #Breakes single list of land_level into separete lists depending on the number of datapoints and columns (n) we want/have in the dataframe.
#print(land_level_matrix)

land_level_df = pd.DataFrame(land_level_matrix)             #Generates land_level_df from the segmented list above
print(land_level_df)


def mySqrt(x: int) -> int:
    if x == 0:
        return 0

    if x == 1:
        return 1

    left = 0
    right = x // 2
    mid = (left + right + 1) // 2
    while left < right:
        mid = (right + left + 1) // 2
        if mid**2 > x:
            right = mid - 1
        elif mid**2 < x:
            left = mid
        else:
            return int(mid)

    return int(left)

if __name__ == "__main__":
    print(mySqrt(10))


import random
import copy
DELTA = 2

# Takes a data file organized as CRF++ requires and splits it into
# train and data files.
# Args:
# data_filename - the name of the file that should be sliced.
# percent - the percentage of train data out of total data (range 1-100).
# delta - range allowed to be different from given percentage. (range 0-100 , a too small/big delta is on user
# responsibility).
# unique_str -  to add to the file name, defaults to none.
# Creates train_data + index + _filename and test + index + _data_filename
# Returns a list of the new files created: test, train.
def create_split(data_filename, percent, delta, unique_str=""):
    percent = float(percent) / 100
    delta = float(delta) / 100
    # A 0/1 flag to indicate where the data goes now.
    flag_train_test = which_now(percent)
    train_file_name = "train_" + unique_str+ data_filename
    test_file_name = "test_" + unique_str + data_filename
    train = open(train_file_name, 'w+', encoding="utf-8")
    test = open(test_file_name , 'w+',  encoding="utf-8")
    files = [train, test]
    lengths = [0, 0]
    with open(data_filename, 'r', encoding="utf-8") as data:
        for line in data:
            files[flag_train_test].write(line)
            lengths[flag_train_test] += 1
            if not line.strip("\n").strip(" "):
                flag_train_test = which_now(percent)
    for i in range(2):
        files[i].seek(0)
    # Variables for sentences transfer, assuming only one file to another transfer and no back and forth
    number_of_lines_transfer = 0
    file_transfer = 0
    # Computing how many lines should be transferred
    number_of_lines_transfer = 0
    while True:
        flag = is_unbalanced(lengths, percent, delta) # Flag that indicate if data is sliced correct
        # and if not which is bigger.
        if not flag:
            break
        else:  # Transfer from one file to another, flag indicates which is the bigger file.
            flag -= 1
            file_transfer = flag
            line = files[flag].readline()
            number_of_lines_transfer += 1
            while line.strip("\n").strip(" ") != "":
                number_of_lines_transfer += 1
                line = files[flag].readline()
            lengths[flag] -= number_of_lines_transfer
            lengths[int(not flag)] += number_of_lines_transfer
    # Transfer lines if needed
    print("Lengthes of files are: " + str(lengths[0]) + " test- " + str(lengths[1]))  # todo
    print("Number of line to trans: " + str(number_of_lines_transfer))  # todo
    if number_of_lines_transfer != 0:
        to_transfer_file = int(not file_transfer)
        files[to_transfer_file].seek(0, 2)  # seek end of file
        files[file_transfer].seek(0)
        for i in range(number_of_lines_transfer):
            line = files[file_transfer].readline()
            files[to_transfer_file].write(line)
        files[file_transfer].seek(0)
        for i in range(number_of_lines_transfer):
            files[file_transfer].write("\n")
    for i in range(2):
        files[i].close()
    return [train_file_name, test_file_name]

# Appends sec file to first file
def append_files(first_file, sec_file):
    f = open(first_file, 'a', encoding="utf-8")
    with open(sec_file, 'r', encoding="utf-8") as s:
        f.write(s.read())
    f.close()

# Creates 5 files for cross validation. Uses create split so names formats of names listed there.
# Receives the corpus file name and unique_str to add to file names
# Returns a list with 2 lists: [[train files names], [test files names]]
def create_cross_valid(data_filename, unique_str):
    train_files = []
    test_files = []
    file_to_split = data_filename
    for i in range(0, 4):
        split = create_split(file_to_split, 100 * (4 - i)/(5 - i), DELTA, str(i + 1) + "_" + unique_str)
        file_to_split = split[0]
        train_files.append(split[0])
        test_files.append(split[1])
    new_train_file = "train_" + "5_" + unique_str + data_filename
    train_files.append(new_train_file)
    open(new_train_file, "w", encoding="utf-8").close()
    new_test_file = "test" + "5_" + unique_str + data_filename
    test_files.append(new_test_file)
    open(new_test_file, "w", encoding="utf-8").close()
    append_files(new_test_file, file_to_split)
    for i in range(2, 6):
        for j in range(1, i-1):
            append_files(train_files[i - 1], test_files[j - 1])
    # first_split = create_split(data_filename, 80, DELTA, "1_" + unique_str)
    # train_files.append(first_split[0])
    # test_files.append(first_split[1])
    # sec_split = create_split(train_files[0], 75, DELTA, "2_" + unique_str)
    # test_files.append(sec_split[1])
    # # append first test set to sec train
    # append_files(sec_split[0], test_files[0])
    # train_files.append(sec_split[0])
    # third_split = create_split(train_files[1], 50, DELTA, "3_" + unique_str)
    # test_files.append(third_split[0])
    # test_files.append(third_split[1])
    # # append three others to both results of the third split
    # new_third = "train_" + "3_" + unique_str + data_filename
    # new_forth = "train_" + "4_" + unique_str + data_filename
    # open(new_third, "w", encoding="utf-8").close()
    # open(new_forth, "w", encoding="utf-8").close()
    # train_files.append(new_third)
    # train_files.append(new_forth)
    # for i, test_file in enumerate(test_files):
    #     if i != 3:
    #         append_files(new_third, test_file)
    #     if i != 4:
    #         append_files(new_forth, test_file)
    return [train_files, test_files]

def which_now(percent):
    if random.random() < percent:
        return 0
    else:
        return 1

# Checks if the train/test data is sliced correctly.
# Returns False is so, and 1 to indicate train file is too big and 2 for too small.
def is_unbalanced(lengths, percent, delta):
    train_percentage = float(lengths[0]) / (lengths[0] + lengths[1])
    print("Train percantge: " + str(train_percentage))
    print("Length 1: " + str(lengths[0]) + " length 2: " + str(lengths[1]))
    if train_percentage > (percent + delta) :
        return 1
    if train_percentage < (percent - delta):
        return 2
    return False

# ---- New version, all togther for cross validation.
# Returns a number between 0-4 to indicate which test file will get next sentence
def which_slice_now(tot_length, test_lengths):
    big_enough_files = []
    zeroes_count = 0
    for i, length in enumerate(test_lengths):
        zeroes_count += int(length == 0)
        if length/tot_length > 0.2:
            big_enough_files.append(i)
    next_slice = random.randint(0, 4)
    while next_slice in big_enough_files:
        next_slice = random.randint(0, 4)
    if zeroes_count == 1:
        return test_lengths.index(0)
    return next_slice

def cross_validate(data_filename, unique_str):
    with open(data_filename, "r", encoding="utf-8") as corp:
        lines = corp.readlines()
    test_content = [[] for i in range(5)]
    tot_len = len(lines)
    test_lengths = [0 for j in range(5)]
    current_slice = which_slice_now(tot_len, test_lengths)
    for line in lines:
        test_content[current_slice].append(line)
        if line == "\n":
            tot_len -= 1
            current_slice = which_slice_now(tot_len, test_lengths)
        else:
            test_lengths[current_slice] += 1
    test_files = []
    train_files = []
    for i in range(5):
        test_name =  "test_" + unique_str + str(i + 1) + "_" + data_filename
        train_name = "train_" + unique_str + str(i + 1) + "_" + data_filename
        test_file = open(test_name, "w", encoding="utf-8")
        test_file.writelines(test_content[i])
        test_file.close()
        train_file = open(train_name, "w", encoding="utf-8")
        for j in range(5):
            if j != i:
                train_file.writelines(test_content[j])
        train_file.close()
        test_files.append(test_name)
        train_files.append(train_name)
    return [train_files, test_files]
t = cross_validate("organized_corp.txt", "fds")

# create_split(, 80, 2)
# t = create_cross_valid("dugma_simple.txt", "gTes_")
# t = create_split("dugma_long.txt", 80, 2,"gTes_")
# print(t)
for file in t[1]:
    print("number of lines in file: " + file + " are: ")
    print(len(open(file, "r", encoding="utf-8").readlines()))
    print("\n")


import torch.nn as nn
import torch
import torch.nn.functional as F
from torch import Tensor
from typing import Tuple, Dict
import math
from torchsummary import summary
from torch.nn.modules import ModuleList, Identity
from collections import OrderedDict

def PatchConvSASPPSE_MViT():
    model = PatchConvS_ASPP_SE_MViT(blocks=[1, 1, 1, 2], ratios=2, channels=64, dims=[64, 128, 256, 512])
    return model

class patchconv(nn.Module):
    def __init__(self, patch_size=(4, 4), in_dims=3, out_dims=16):
        super(patchconv, self).__init__()
        self.conv = nn.Sequential(nn.Conv2d(in_channels=in_dims, out_channels=out_dims, kernel_size=patch_size,
                                            stride=patch_size, padding=(0, 0), bias=False),
                                  nn.BatchNorm2d(out_dims),
                                  nn.LeakyReLU(negative_slope=0.2, inplace=True))

    def forward(self, x):
        x = self.conv(x)
        return x

class Resblock(nn.Module):
    def __init__(self, in_dims):
        super(Resblock, self).__init__()
        self.conv = nn.Sequential(nn.Conv2d(in_channels=in_dims, out_channels=in_dims, kernel_size=(3, 3),
                                            stride=(1, 1), padding=(1, 1), bias=False),
                                  nn.BatchNorm2d(in_dims),
                                  nn.LeakyReLU(negative_slope=0.2, inplace=True),
                                  nn.Conv2d(in_channels=in_dims, out_channels=in_dims, kernel_size=(3, 3),
                                            stride=(1, 1), padding=(1, 1), bias=False),
                                  nn.BatchNorm2d(in_dims),
                                  nn.LeakyReLU(negative_slope=0.2, inplace=True))

    def forward(self, x):
        residual = x
        x = self.conv(x)
        out = x + residual
        return out

class BasicRes(nn.Module):
    def __init__(self, num_blocks, dims, ratios, downsample=True):
        super(BasicRes, self).__init__()
        self.blocks = ModuleList()
        self.downsample = patchconv(patch_size=(2, 2), in_dims=dims, out_dims=dims*ratios) if downsample else Identity()
        for i in range(num_blocks):
            block = Resblock(in_dims=dims)
            self.blocks.append(block)

    def forward(self, x):
        for blk in self.blocks:
            x = blk(x)
        x = self.downsample(x)
        return x

class Upsample(nn.Module):
    def __init__(self, in_dims, out_dims):
        super(Upsample, self).__init__()
        self.conv = nn.Sequential(nn.Conv2d(in_channels=in_dims, out_channels=out_dims, kernel_size=(5, 5),
                                            stride=(1, 1), padding=(2, 2), bias=False),
                                  nn.BatchNorm2d(out_dims),
                                  nn.LeakyReLU(negative_slope=0.2, inplace=True))

    def forward(self, x):
        x = self.conv(x)
        return x

class Dropout(nn.Dropout):
    def __init__(self, p: float = 0.5, inplace: bool = False):
        """
        During training, randomly zeroes some of the elements of the input tensor with probability `p` using samples \
        from a Bernoulli distribution.

        :param p: probability of an element to be zeroed. Default: 0.5
        :param inplace: If set to ``True``, will do this operation in-place. Default: ``False``
        """
        super(Dropout, self).__init__(p=p, inplace=inplace)

    def profile_module(self, input: Tensor) -> (Tensor, float, float):
        input = self.forward(input)
        return input, 0.0, 0.0

class SEblock(nn.Module):
    def __init__(self, in_dim):
        super(SEblock, self).__init__()
        squeeze = int(in_dim // 16)
        self.fc1 = nn.Conv2d(in_dim, squeeze, (1, 1))
        self.fc2 = nn.Conv2d(squeeze, in_dim, (1, 1))

    def forward(self, x):
        scale = F.adaptive_avg_pool2d(x, output_size=(1, 1))
        scale = self.fc1(scale)
        scale = F.leaky_relu_(scale)
        scale = self.fc2(scale)
        scale = torch.sigmoid(scale)
        return scale * x

class ASPPConv(nn.Sequential):
    def __init__(self, in_channels: int, out_channels: int, dilation: int) -> None:
        super(ASPPConv, self).__init__(
            nn.Conv2d(in_channels, out_channels, 3, padding=dilation, dilation=dilation, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.LeakyReLU(negative_slope=0.2, inplace=True)
        )

class ASPPPooling(nn.Sequential):
    def __init__(self, in_channels: int, out_channels: int) -> None:
        super(ASPPPooling, self).__init__(
            nn.AdaptiveAvgPool2d(1),
            nn.Conv2d(in_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.LeakyReLU(negative_slope=0.2, inplace=True)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        size = x.shape[-2:]
        for mod in self:
            x = mod(x)
        return F.interpolate(x, size=size, mode='bilinear', align_corners=False)

class ASPP(nn.Module):
    def __init__(self, in_channels: int, atrous_rates, out_channels: int = 256) -> None:
        super(ASPP, self).__init__()
        modules = [
            nn.Sequential(nn.Conv2d(in_channels, out_channels, 1, bias=False),
                          nn.BatchNorm2d(out_channels),
                          nn.LeakyReLU(negative_slope=0.2, inplace=True))
        ]

        rates = tuple(atrous_rates)
        for rate in rates:
            modules.append(ASPPConv(in_channels, out_channels, rate))

        modules.append(ASPPPooling(in_channels, out_channels))

        self.convs = nn.ModuleList(modules)

        self.project = nn.Sequential(
            nn.Conv2d(len(self.convs) * out_channels, out_channels, 1, bias=False),
            nn.BatchNorm2d(out_channels),
            nn.LeakyReLU(negative_slope=0.2, inplace=True),
            nn.Dropout(0.5)
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        _res = []
        for conv in self.convs:
            _res.append(conv(x))
        res = torch.cat(_res, dim=1)
        return self.project(res)

class LinearLayer(nn.Module):
    def __init__(self,
                 in_features: int,
                 out_features: int,
                 bias = True,
                 *args, **kwargs) -> None:
        """
            Applies a linear transformation to the input data

            :param in_features: size of each input sample
            :param out_features:  size of each output sample
            :param bias: Add bias (learnable) or not
        """
        super(LinearLayer, self).__init__()
        self.weight = nn.Parameter(torch.Tensor(out_features, in_features))
        self.bias = None
        if bias:
            self.bias = nn.Parameter(torch.Tensor(out_features))
        self.in_features = in_features
        self.out_features = out_features
        self.reset_params()

    def reset_params(self):
        if self.weight is not None:
            torch.nn.init.xavier_uniform_(self.weight)
        if self.bias is not None:
            torch.nn.init.constant_(self.bias, 0)

    def forward(self, x: Tensor) -> Tensor:
        if self.bias is not None and x.dim() == 2:
            x = torch.addmm(self.bias, x, self.weight.t())
        else:
            x = x.matmul(self.weight.t())
            if self.bias is not None:
                x += self.bias
        return x

class MultiHeadAttention(nn.Module):
    def __init__(self, embed_dim, num_heads, attn_dropout, bias=True):
        super(MultiHeadAttention, self).__init__()
        self.qkv_proj = LinearLayer(in_features=embed_dim, out_features=3 * embed_dim, bias=bias)

        self.attn_dropout = Dropout(p=attn_dropout)
        self.out_proj = LinearLayer(in_features=embed_dim, out_features=embed_dim, bias=bias)

        self.head_dim = embed_dim // num_heads
        self.scaling = self.head_dim ** -0.5
        self.softmax = nn.Softmax(dim=-1)
        self.num_heads = num_heads
        self.embed_dim = embed_dim

    def forward_other(self, x: Tensor) -> Tensor:
        # [B x N x C]
        b_sz, n_patches, in_channels = x.shape

        # [B x N x C] --> [B x N x 3 x h x C]
        qkv = (
            self.qkv_proj(x)
                .reshape(b_sz, n_patches, 3, self.num_heads, -1)
        )
        # [B x N x 3 x h x C] --> [B x h x 3 x N x C]
        qkv = qkv.transpose(1, 3)

        # [B x h x 3 x N x C] --> [B x h x N x C] x 3
        query, key, value = qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2]

        query = query * self.scaling

        # [B x h x N x C] --> [B x h x c x N]
        key = key.transpose(2, 3)

        # QK^T
        # [B x h x N x c] x [B x h x c x N] --> [B x h x N x N]
        attn = torch.matmul(query, key)
        attn = self.softmax(attn)
        attn = self.attn_dropout(attn)

        # weighted sum
        # [B x h x N x N] x [B x h x N x c] --> [B x h x N x c]
        out = torch.matmul(attn, value)

        # [B x h x N x c] --> [B x N x h x c] --> [B x N x C=ch]
        out = out.transpose(1, 2).reshape(b_sz, n_patches, -1)
        out = self.out_proj(out)

        return out

    def forward(self, x: Tensor) -> Tensor:
        return self.forward_other(x)

class TransformerBlock(nn.Module):
    def __init__(self, embed_dim, ffn_latent_dim, num_heads, attn_dropout, ffn_dropout, dropout):
        super(TransformerBlock, self).__init__()
        self.LN1 = nn.Sequential(nn.LayerNorm(embed_dim))
        self.MSAttn = MultiHeadAttention(embed_dim, num_heads=num_heads, attn_dropout=attn_dropout, bias=True)
        self.Drop1 = Dropout(p=dropout)
        self.LN2 = nn.Sequential(nn.LayerNorm(embed_dim))
        self.linear1 = LinearLayer(embed_dim, ffn_latent_dim, bias=True)
        self.act = nn.Sequential(nn.ReLU(inplace=False))
        self.Drop2 = Dropout(p=ffn_dropout)
        self.linear2 = LinearLayer(ffn_latent_dim, embed_dim,  bias=True)
        self.Drop3 = Dropout(p=dropout)

    def forward(self, x):
        res1 = x
        x = self.LN1(x)
        x = self.MSAttn(x)
        x = self.Drop1(x)
        res2 = res1 + x
        x = self.LN2(res2)
        x = self.linear1(x)
        x = self.act(x)
        x = self.Drop2(x)
        x = self.linear2(x)
        x = self.Drop3(x)
        x = res2 + x
        return x

class standard_down_conv(nn.Module):
    def __init__(self, in_dims, out_dims):
        super(standard_down_conv, self).__init__()
        self.conv = nn.Sequential(nn.Conv2d(in_channels=in_dims, out_channels=out_dims, kernel_size=(3, 3),
                                            stride=(2, 2), padding=(1, 1), bias=False),
                                  nn.BatchNorm2d(out_dims),
                                  nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.resconv = Resblock(out_dims)

    def forward(self, x):
        x = self.conv(x)
        x = self.resconv(x)
        return x

class MobileViTBlock(nn.Module):
    def __init__(self, in_channels, n_transformer_blocks, ffn_latent_dim, patch_w, patch_h,
                 num_heads=4, attn_dropout=0.0, ffn_dropout=0.0, dropout=0.1, fusion=True):
        super(MobileViTBlock, self).__init__()
        # self.conv5X5in = nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size=(5, 5),
        #                                          stride=(1, 1), padding=(2, 2), bias=False),
        #                                nn.BatchNorm2d(in_channels),
        #                                nn.LeakyReLU(negative_slope=0.2, inplace=True))
        # self.conv1X1in = nn.Sequential(nn.Conv2d(in_channels, embed_dim, kernel_size=(1, 1),
        #                                          stride=(1, 1), padding=(0, 0), bias=False),
        #                                nn.BatchNorm2d(embed_dim),
        #                                nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.global_rep = nn.ModuleList()
        for i in range(n_transformer_blocks):
            global_rep = TransformerBlock(in_channels, ffn_latent_dim, num_heads, attn_dropout, ffn_dropout, dropout)
            self.global_rep.append(global_rep)
        # self.conv1X1out = nn.Sequential(nn.Conv2d(embed_dim, in_channels, kernel_size=(1, 1),
        #                                           stride=(1, 1), padding=(0, 0), bias=False),
        #                                 nn.BatchNorm2d(in_channels),
        #                                 nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.conv5X5out = nn.Sequential(nn.Conv2d(in_channels * 2, in_channels, kernel_size=(5, 5),
                                                  stride=(1, 1), padding=(2, 2), bias=False),
                                        nn.BatchNorm2d(in_channels),
                                        nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.fusion = fusion
        self.patch_w = patch_w
        self.patch_h = patch_h
        self.patch_area = patch_h * patch_w

    def unfolding(self, feature_map: Tensor) -> Tuple[Tensor, Dict]:
        patch_w, patch_h = self.patch_w, self.patch_h
        patch_area = int(patch_w * patch_h)
        batch_size, in_channels, orig_h, orig_w = feature_map.shape

        new_h = int(math.ceil(orig_h / self.patch_h) * self.patch_h)
        new_w = int(math.ceil(orig_w / self.patch_w) * self.patch_w)

        interpolate = False
        if new_w != orig_w or new_h != orig_h:
            # Note: Padding can be done, but then it needs to be handled in attention function.
            feature_map = F.interpolate(feature_map, size=(new_h, new_w), mode="bilinear", align_corners=False)
            interpolate = True

        # number of patches along width and height
        num_patch_w = new_w // patch_w # n_w
        num_patch_h = new_h // patch_h # n_h
        num_patches = num_patch_h * num_patch_w # N

        # [B, C, H, W] --> [B * C * n_h, p_h, n_w, p_w]
        reshaped_fm = feature_map.reshape(batch_size * in_channels * num_patch_h, patch_h, num_patch_w, patch_w)
        # [B * C * n_h, p_h, n_w, p_w] --> [B * C * n_h, n_w, p_h, p_w]
        transposed_fm = reshaped_fm.transpose(1, 2)
        # [B * C * n_h, n_w, p_h, p_w] --> [B, C, N, P] where P = p_h * p_w and N = n_h * n_w
        reshaped_fm = transposed_fm.reshape(batch_size, in_channels, num_patches, patch_area)
        # [B, C, N, P] --> [B, P, N, C]
        transposed_fm = reshaped_fm.transpose(1, 3)
        # [B, P, N, C] --> [BP, N, C]
        patches = transposed_fm.reshape(batch_size * patch_area, num_patches, -1)

        info_dict = {
            "orig_size": (orig_h, orig_w),
            "batch_size": batch_size,
            "interpolate": interpolate,
            "total_patches": num_patches,
            "num_patches_w": num_patch_w,
            "num_patches_h": num_patch_h
        }

        return patches, info_dict

    def folding(self, patches: Tensor, info_dict: Dict) -> Tensor:
        n_dim = patches.dim()
        assert n_dim == 3, "Tensor should be of shape BPxNxC. Got: {}".format(patches.shape)
        # [BP, N, C] --> [B, P, N, C]
        patches = patches.contiguous().view(info_dict["batch_size"], self.patch_area, info_dict["total_patches"], -1)

        batch_size, pixels, num_patches, channels = patches.size()
        num_patch_h = info_dict["num_patches_h"]
        num_patch_w = info_dict["num_patches_w"]

        # [B, P, N, C] --> [B, C, N, P]
        patches = patches.transpose(1, 3)

        # [B, C, N, P] --> [B*C*n_h, n_w, p_h, p_w]
        feature_map = patches.reshape(batch_size * channels * num_patch_h, num_patch_w, self.patch_h, self.patch_w)
        # [B*C*n_h, n_w, p_h, p_w] --> [B*C*n_h, p_h, n_w, p_w]
        feature_map = feature_map.transpose(1, 2)
        # [B*C*n_h, p_h, n_w, p_w] --> [B, C, H, W]
        feature_map = feature_map.reshape(batch_size, channels, num_patch_h * self.patch_h, num_patch_w * self.patch_w)
        if info_dict["interpolate"]:
            feature_map = F.interpolate(feature_map, size=info_dict["orig_size"], mode="bilinear", align_corners=False)
        return feature_map

    def forward(self, x: Tensor) -> Tensor:
        res = x
        # x = self.conv5X5in(x)
        # fm = self.conv1X1in(x)
        # convert feature map to patches
        patches, info_dict = self.unfolding(x)
        # learn global representations
        for i, gr in enumerate(self.global_rep):
            patches = gr(patches)
        # [B x Patch x Patches x C] --> [B x C x Patches x Patch]
        fm = self.folding(patches=patches, info_dict=info_dict)

        # fm = self.conv1X1out(fm)
        if self.fusion:
            fm = self.conv5X5out(torch.cat((res, fm), dim=1))
        return fm

class PatchConvS_ASPP_SE_MViT(nn.Module):
    def __init__(self, blocks, dims, ratios, channels):
        super(PatchConvS_ASPP_SE_MViT, self).__init__()
        self.patch_conv = patchconv(patch_size=(2, 2), in_dims=3, out_dims=channels)
        self.stages = nn.ModuleList()
        for i in range(0, len(blocks)):
            stage = BasicRes(num_blocks=blocks[i], dims=dims[i], ratios=ratios, downsample=(i + 1 < len(blocks)))
            self.stages.append(stage)
        self.ASPP = ASPP(dims[3], atrous_rates=[6, 12, 18], out_channels=dims[3])
        self.SE = SEblock(dims[3])
        self.up1 = Upsample(dims[2], dims[1])
        self.up2 = Upsample(dims[1], dims[0])
        self.up3 = Upsample(dims[0], dims[0])
        self.pwconv0 = nn.Sequential(nn.Conv2d(dims[3], dims[2], kernel_size=(1, 1), stride=(1, 1), padding=(0, 0), bias=False),
                                     nn.BatchNorm2d(dims[2]),
                                     nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.MobileViT_Block = MobileViTBlock(dims[2], n_transformer_blocks=1, ffn_latent_dim=dims[2]*3,
                                              patch_w=2, patch_h=2)
        self.pwconv = nn.Sequential(nn.Conv2d(dims[0], 1, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0), bias=False),
                                    nn.BatchNorm2d(1),
                                    nn.LeakyReLU(negative_slope=0.2, inplace=True))

    def forward(self, x):
        concat_block = []
        x = self.patch_conv(x)
        concat_block.append(x)
        for i, stage in enumerate(self.stages):
            x = stage(x)
            if i < 3:
                concat_block.append(x)
        x = self.ASPP(x)
        x = self.SE(x)
        x = self.pwconv0(x)
        x = self.MobileViT_Block(x)
        x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)
        x = x + concat_block[2]
        x = self.up1(x)
        x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)
        x = x + concat_block[1]
        x = self.up2(x)
        x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)
        x = x + concat_block[0]
        x = self.up3(x)
        x = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=True)
        x = self.pwconv(x)
        return x

class PatchConvS_ASPP_SE_MViT_Seg(nn.Module):
    def __init__(self, blocks, dims, ratios, channels, num_classes):
        super(PatchConvS_ASPP_SE_MViT_Seg, self).__init__()
        self.patch_conv = patchconv(patch_size=(2, 2), in_dims=3, out_dims=channels)
        self.stages = nn.ModuleList()
        for i in range(0, len(blocks)):
            stage = BasicRes(num_blocks=blocks[i], dims=dims[i], ratios=ratios, downsample=(i + 1 < len(blocks)))
            self.stages.append(stage)
        self.ASPP = ASPP(dims[3], atrous_rates=[6, 12, 18], out_channels=dims[3])
        self.SE = SEblock(dims[3])
        self.pwconv0 = nn.Sequential(nn.Conv2d(dims[3], dims[2], kernel_size=(1, 1), stride=(1, 1), padding=(0, 0), bias=False),
                                     nn.BatchNorm2d(dims[2]),
                                     nn.LeakyReLU(negative_slope=0.2, inplace=True))
        self.MobileViT_Block = MobileViTBlock(dims[2], n_transformer_blocks=1, ffn_latent_dim=dims[2]*3,
                                              patch_w=2, patch_h=2)
        self.classifier = nn.Sequential(nn.Conv2d(dims[2], dims[2], kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False),
                                        nn.BatchNorm2d(dims[2]),
                                        nn.LeakyReLU(negative_slope=0.2, inplace=True),
                                        nn.Conv2d(dims[2], num_classes, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0)))
        # self.conv1 = nn.Sequential(nn.Conv2d(num_classes, num_classes, kernel_size=(1, 1), stride=(1, 1), padding=(0, 0), bias=False),
        #                            nn.BatchNorm2d(num_classes),
        #                            nn.LeakyReLU(negative_slope=0.2, inplace=True))

    def forward(self, x):
        result = OrderedDict()
        x = self.patch_conv(x)
        for i, stage in enumerate(self.stages):
            x = stage(x)
        x = self.ASPP(x)
        x = self.SE(x)
        x = self.pwconv0(x)
        x = self.MobileViT_Block(x)
        x = self.classifier(x)
        x = F.interpolate(x, size=(224, 224), mode='bilinear', align_corners=False)
        # x = self.conv1(x)
        result["out"] = x
        return result

if __name__ == '__main__':
    net = PatchConvS_ASPP_SE_MViT(blocks=[1, 1, 1, 2], ratios=2, channels=64, dims=[64, 128, 256, 512]).cpu()
    summary(net, (3, 224, 224), device='cpu')


import random
import logging

logger = logging.getLogger()

import merc
import interp
import fight
import game_utils
import handler_game
import state_checks
import const

def do_steal(ch, argument):
    argument, arg1 = game_utils.read_word(argument)
    argument, arg2 = game_utils.read_word(argument)

    if not arg1 or not arg2:
        ch.send("Steal what from whom?\n")
        return
    victim = ch.get_char_room(arg2)
    if not victim:
        ch.send("They aren't here.\n")
        return
    if victim == ch:
        ch.send("That's pointless.\n")
        return
    if fight.is_safe(ch, victim):
        return

    if victim.is_npc() and victim.position == merc.POS_FIGHTING:
        ch.send("Kill stealing is not permitted.\nYou'd better not -- you might get hit.\n")
        return
    state_checks.WAIT_STATE(ch, const.skill_table["steal"].beats)
    percent = random.randint(1, 99)

    if not state_checks.IS_AWAKE(victim):
        percent -= 10
    elif not victim.can_see(ch):
        percent += 25
    else:
        percent += 50

    if ((ch.level + 7 < victim.level or ch.level - 7 > victim.level)
        and not victim.is_npc() and not ch.is_npc() ) \
            or (not ch.is_npc() and percent > ch.get_skill("steal")) \
            or (not ch.is_npc() and not ch.is_clan()):
        # Failure.
        ch.send("Oops.\n")
        ch.affect_strip("sneak")
        ch.affected_by = ch.affected_by.rem_bit(merc.AFF_SNEAK)
        handler_game.act("$n tried to steal from you.\n", ch, None, victim, merc.TO_VICT)
        handler_game.act("$n tried to steal from $N.\n", ch, None, victim, merc.TO_NOTVICT)
        outcome = random.randint(0, 3)
        buf = ''
        if outcome == 0:
            buf = "%s is a lousy thief!" % ch.name
        elif outcome == 1:
            buf = "%s couldn't rob %s way out of a paper bag!" % (ch.name, ("her" if ch.sex == 2 else "his"))
        elif outcome == 2:
            buf = "%s tried to rob me!" % ch.name
        elif outcome == 3:
            buf = "Keep your hands out of there, %s!" % ch.name
        if not state_checks.IS_AWAKE(victim):
            victim.do_wake("")
        if state_checks.IS_AWAKE(victim):
            victim.do_yell(buf)
        if not ch.is_npc():
            if victim.is_npc():
                if ch.is_pc():
                    ch.check_improve("steal", False, 2)
                fight.multi_hit(victim, ch, merc.TYPE_UNDEFINED)
            else:
                handler_game.wiznet("$N tried to steal from %s." % victim.name, ch, None, merc.WIZ_FLAGS, 0, 0)
                if not ch.act.is_set(merc.PLR_THIEF):
                    ch.act.set_bit(merc.PLR_THIEF)
                    ch.send("*** You are now a THIEF!! ***\n")
                    ch.save()
        return
    currency = ['coins', 'coin', 'gold', 'silver']
    if arg1 in currency:
        gold = victim.gold * random.randint(1, ch.level) // merc.MAX_LEVEL
        silver = victim.silver * random.randint(1, ch.level) // merc.MAX_LEVEL
        if gold <= 0 and silver <= 0:
            ch.send("You couldn't get any coins.\n")
            return
        ch.gold += gold
        ch.silver += silver
        victim.silver -= silver
        victim.gold -= gold
        if silver <= 0:
            ch.send("Bingo!  You got %d gold coins.\n" % gold)
        elif gold <= 0:
            ch.send("Bingo!  You got %d silver coins.\n" % silver)
        else:
            ch.send("Bingo!  You got %d silver and %d gold coins.\n" % (silver, gold))
        if ch.is_pc():
            ch.check_improve( "steal", True, 2)
        return
    item = victim.get_item_carry(arg1, ch)
    if not item:
        ch.send("You can't find it.\n")
        return
    if not ch.can_drop_item(item) or item.flags.shop_inventory or item.level > ch.level:
        ch.send("You can't pry it away.\n")
        return
    if ch.carry_number + item.get_number() > ch.can_carry_n():
        ch.send("You have your hands full.\n")
        return
    if ch.carry_weight + item.get_weight() > ch.can_carry_w():
        ch.send("You can't carry that much weight.\n")
        return
    item.get()
    ch.put(item)
    handler_game.act("You pocket $p.", ch, item, None, merc.TO_CHAR)
    if ch.is_pc():
        ch.check_improve( "steal", True, 2)
    ch.send("Got it!\n")
    return

interp.register_command(interp.cmd_type('steal', do_steal, merc.POS_STANDING, 0, merc.LOG_NORMAL, 1))


import jax
import pyscf
from pyscfad import gto, scf, mp

"""
Analytic nuclear gradient for MP2 computed by auto-differentiation
"""

mol = gto.Mole()
mol.atom = 'H 0 0 0; H 0 0 0.74'  # in Angstrom
mol.basis = '631g'
mol.verbose=5
mol.build()

def mp2(mol, dm0=None):
    mf = scf.RHF(mol)
    mf.kernel(dm0)
    mymp = mp.MP2(mf)
    mymp.kernel()
    return mymp.e_tot

jac = jax.grad(mp2)(mol)
print(f'Nuclaer gradient:\n{jac.coords}')
print(f'Gradient wrt basis exponents:\n{jac.exp}')
print(f'Gradient wrt basis contraction coefficients:\n{jac.ctr_coeff}')


xs = int(input())
res = []

def aux(res, ind, one, five, ten):
    if ind > 5:
        res.append((five + one * (ind - 5)) if ind < 9 else
                   one + ten)
    else:
        res.append(one * ind if ind < 4 else
                   one + five if ind == 4 else
                   five)

th = xs // 1000
aux(res, th, 'M', '', '')
xs %= 1000
hu = xs // 100
aux(res, hu, 'C', 'D', 'M')
xs %= 100
te = xs // 10
aux(res, te, 'X', 'L', 'C')
xs %= 10
aux(res, xs, 'I', 'V', 'X')
print(''.join(res))


#!/usr/bin/env python
# coding=utf-8
import os
import hashlib
import datetime
import json
import urllib
import time

from django.conf import settings

from qiniu import Auth
from qiniu import put_data

from utils.log_util import error_logger

def _upload_file_name(tempfilename, prefix=None):
    if not tempfilename:
        return None
    if not prefix:
        prefix = datetime.datetime.today().strftime("%Y/%m/%d")
    md5 = hashlib.md5(str(time.time()).encode("utf8")).hexdigest()[:10]
    md5 = prefix + '/' + md5
    shotname, extension = os.path.splitext(tempfilename)
    if extension:
        md5 = '{}{}'.format(md5, extension)
    return md5

def upload_file(file, prefix=None):
    q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
    token = q.upload_token(settings.QINIU_SCOPE)

    file_name = _upload_file_name(file.name, prefix)
    response = put_data(
            token,
            file_name,
            file,
            params=None,
            mime_type='application/octet-stream',
            check_crc=False,
            progress_handler=None,
        )
    if response and response[0].get('key'):
        key = response[0].get('key')
        return {'code': 0, 'message': '上传成功', 'data': {'file_path': key}}
    else:
        error_logger.error('qiniu==>response: %s' % json.dumps(response))
        return {'code': 1, 'message': '上传失败，请重试', 'data': response}

def get_full_path(path_name, extra=''):
    if not path_name:
        return None
    full_path = urllib.parse.urljoin(settings.QINIU_HOST, path_name)
    return full_path + extra


"""
Datos de entrada
precio al contado-->pac-->int
precio cuotas-->pc-->float
Datos de salida
porcentaje de recargo-->pr-->float
"""
#Entradas
pac=int(input("Digite el precio a pagar por contado "))
pc=float(input("Digite el precio a pagar por cuotas "))
#Caja negra
pr=(((pc-pac)/12)*100)/pac
#Salidas
print(f"El porcentaje de recargo mensual es del {pr}"+"%")


t=int(input())
for ti in range(t):
    n=int(input())
    s=input().split(' ')
    k=int(input())
    co=0
    li=[]
    for i in range(n):
        for j in range(i+1,n):
            if int(s[i]) > int(s[j]) and [s[i],s[j]] not in li:
                li.append([s[i],s[j]])
            elif int(s[j]) >= int(s[i]) and [s[j],s[i]] not in li:
                li.append([s[j],s[i]])
    for ki in li:
        if int(ki[0])-int(ki[1])==k:
            co=co+1
    print(co)


#! /usr/bin/env python

#This file is taken from "https://gist.github.com/jeetsukumaran/2225546". We have slightly modified it.

import os
import sys

if ("--help" in sys.argv) or ("-?" in sys.argv):
    sys.stderr.write("usage: fasta-to-nexus.py [<fasta-file-path>] [<nexus-file-path>]\n")
    sys.exit(1)

if len(sys.argv) < 2:
    src = sys.stdin
else:
    src_fpath = os.path.expanduser(os.path.expandvars(sys.argv[1]))
    if not os.path.exists(src_fpath):
        sys.stderr.write('Not found: "%s"' % src_fpath)
    src = open(src_fpath)

if len(sys.argv) < 3:
    dest = sys.stdout # os.path.splitext(src_fpath)[0] + ".nex"
else:
    dest_fpath = os.path.expanduser(os.path.expandvars(sys.argv[2]))
    dest = open(dest_fpath, "w")

seqs = {}
cur_seq = None
lines = src.readlines()
for i in lines:
    i = i.replace("\n", "").replace("\r", "")
    if i:
        if i.startswith(">"):
            label = i[1:]
            seqs[label] = []
            cur_seq = seqs[label]
        else:
            if cur_seq is None:
                raise Exception("Sequence data found before label")
            cur_seq.extend(i.replace(" ", ""))

taxlabels = seqs.keys()
#taxlabels.sort()

dest.write("#NEXUS\n\n")

dest.write("BEGIN TAXA;\n")
dest.write("\tDIMENSIONS ntax=%d;\n" % len(seqs))
dest.write("\tTAXLABELS ")
for taxlabel in taxlabels:
    dest.write(" %s" % taxlabel)
dest.write(";\n")
dest.write("END;\n\n")

nchar = max([len(s) for s in seqs.values()])
dest.write("BEGIN CHARACTERS;\n")
dest.write("\tDIMENSIONS nchar=%d;\n" % nchar)
dest.write("\tFORMAT datatype=dna missing=? gap=-;\n")
dest.write("\tMATRIX\n")
for taxlabel in taxlabels:
    dest.write("\t%s\t%s\n" % (taxlabel, "".join(seqs[taxlabel])))
dest.write("\t;\n")
dest.write("END;\n")

dest1 = open("data.properties", "w")
count = 0
dest1.write("#property\n")
for taxlabel in taxlabels:
    count = count+1
    dest1.write("%d" % count)
    dest1.write("=%s\n" % taxlabel)


# For detailed implementation see: tests/maze_generator.ipynb
# This implementation has some changes
import numpy as np

class UnionFind:
    def __init__(self, n):
        self.n = n  # number of supernodes
        self.v = [i for i in range(n)]  # represents the parents (initially each disjoint set has a single vertex)

    def find(self, u):
        while u != self.v[u]:
            self.v[u] = self.v[self.v[u]]  # compression technique
            u = self.v[u]

        return u

    def union(self, u, v):
        root_u, root_v = self.find(u), self.find(v)

        if root_u == root_v:
            return False  # union was not performed
        else:
            self.v[root_v] = root_u
            self.n -= 1

            return True  # union was not performed

# Class for the maze generator
# Inspired by a randomized Kruskal algorithm
class KruskalMazeGenerator:
    def __init__(self, N=100):
        self.N = N  # number os cells (default is a 10x10 grid)
        self.shape = int(N**0.5)

        self.walls = self.generate_walls()

    def new_maze(self):
        # Copy the walls (edges) and create a set for each cell
        walls = self.walls.copy()
        forest = UnionFind(self.N)

        # Generate a maze (represented by an adjacency list)
        maze = [[] for _ in range(self.N)]
        while forest.n > 1:
            v, w = walls.pop(np.random.randint(0, len(walls)))

            if forest.union(v, w):
                maze[v].append(w)  # adding (v, w) in the maze
                maze[w].append(v)  # adding (w, v) in the maze

        return maze

    def actions(self, v):  # takes into account the dimensions of the grid
        actions = []

        if v % self.shape != 0:
            actions.append((v, v-1))
        if (v+1) % self.shape != 0:
            actions.append((v, v+1))
        if v >= self.shape:
            actions.append((v, v-self.shape))
        if v+self.shape < self.N:
            actions.append((v, v+self.shape))

        return actions  # possible actions in cell v

    def generate_walls(self):
        walls = []

        # Movement represents the existence or not of a wall
        for v in range(self.N):
            walls.extend(self.actions(v))

        return walls


import itertools
row, max=[],[]

for i in range(9):
    a=list(map(int,input().split()))
    row.append(a)
    sort_a=sorted(a, reverse=True)   #행 숫자큰순서대로
    max.append(sort_a[0])  #각 행 최대값들
all=list(itertools.chain(*row))
max.sort(reverse=True)
ans=all.index(max[0])     #max[0]: 최댓값
r=ans//9+1
c=ans%9+1
print(max[0])
print(r,c)


# https://www.acmicpc.net/problem/1931

import sys

input = sys.stdin.readline

N = int(input())
arr = [list(map(int, input().split())) for _ in range(N)]
arr.sort(key=lambda x: (x[1], x[0]))
cnt = 0

last = -1

for i in arr:
    if i[0] >= last:
        cnt += 1
        last = i[1]

print(cnt)


# -*- coding: utf-8 -*-
# @Time    : 19-5-20 上午10:36
# @Author  : Redtree
# @File    : quick_sort.py
# @Desc :

#----快速排序----
#L：待排序的序列；start排序的开始index,end序列末尾的index
#对于长度为length的序列：start = 0;end = length-1
def dosort(L,start,end):
    if start < end:
        i , j , pivot = start , end , L[start]
        while i < j:
            #从右开始向左寻找第一个小于pivot的值
            while (i < j) and (L[j] >= pivot):
                j = j-1
            #将小于pivot的值移到左边
            if (i < j):
                L[i] = L[j]
                i = i+1
            #从左开始向右寻找第一个大于pivot的值
            while (i < j) and (L[i] < pivot):
                i = i+1
            #将大于pivot的值移到右边
            if (i < j):
                L[j] = L[i]
                j = j-1
            #循环结束后，说明 i=j，此时左边的值全都小于pivot,右边的值全都大于pivot
            #pivot的位置移动正确，那么此时只需对左右两侧的序列调用此函数进一步排序即可
            #递归调用函数：依次对左侧序列：从0 ~ i-1//右侧序列：从i+1 ~ end
        L[i] = pivot
        #左侧序列继续排序
        dosort(L,start,i-1)
        #右侧序列继续排序
        dosort(L,i+1,end)

    return L

#这是递归的写法，如果数组过长，要换非递归的方式


import os
import shutil
import utils.torch_utils as torch_utils
from models.doepd_net import *
from utils.datasets import LoadImages
from utils.utils import load_classes, non_max_suppression, scale_coords, plot_one_box
import random
import time
from pathlib import Path
import cv2
import utils.midas_utils as utils

ONNX_EXPORT = False

def inference(options):
    img_size = (320, 192) if ONNX_EXPORT else options.img_size  # (320, 192) or (416, 256) or (608, 352) for (height, width)
    out, source = options.output, options.source

    device = torch_utils.select_device(device='cpu' if ONNX_EXPORT else options.device)

    if os.path.exists(out):
        shutil.rmtree(out)  # delete output folder
    os.makedirs(out)  # make new output folder

    # Initialize model
    model = DoepdNet(run_mode = options.run_mode, image_size = img_size)

    load_doepd_weights(model, device=device, train_mode=False)
    # Eval mode
    model.to(device).eval()

    dataset = LoadImages(source, img_size=img_size)
    names = load_classes(options.names)
    colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]

    start_time = time.time()
    _ = model(torch.zeros((1, 3, img_size, img_size), device=device)) if device.type != 'cpu' else None  # run once

    for path, img, im0s, _ in dataset:
        img = torch.from_numpy(img).to(device)
        img = img.float()
        img = img.unsqueeze(0)
        # Inference
        time_before_inference = torch_utils.time_synchronized()
        doepd_prediction = model(img)
        time_after_inference = torch_utils.time_synchronized()
        if options.run_mode == 'yolo' or options.run_mode == 'all':
            yolo_prediction = doepd_prediction[0][0]
            # non max supression for yolo output
            yolo_prediction = non_max_suppression(yolo_prediction, options.conf_thres, options.iou_thres, multi_label=False)
                # Process detections
            for _, det in enumerate(yolo_prediction):  # detections per image
                p, s, im0 = path, '', im0s
                save_path = os.path.join(out, os.path.splitext(os.path.basename(p))[0] + "_yolo.png")
                s += '%gx%g ' % img.shape[2:]  # print string
                if det is not None and len(det):
                    # Rescale boxes from img_size to im0 size
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()

                    # Print results
                    for c in det[:, -1].unique():
                        n = (det[:, -1] == c).sum()  # detections per class
                        s += '%g %ss, ' % (n, names[int(c)])  # add to string

                    # Write results
                    for *xyxy, conf, cls in det:
                        label = '%s %.2f' % (names[int(cls)], conf)
                        plot_one_box(xyxy, im0, label=label, color=colors[int(cls)])

                # Print time (inference + NMS)
                print('%sDone.' % s)
                # Save results (image with detections)
                cv2.imwrite(save_path, im0)

        if options.run_mode == 'midas' or options.run_mode == 'all':
            midas_prediction = doepd_prediction[1]
            midas_prediction = (
                torch.nn.functional.interpolate(
                midas_prediction.unsqueeze(1),
                size=im0s.shape[:2],
                mode="bicubic",
                align_corners=False)
                .detach()
                .squeeze()
                .cpu()
                .numpy()
            )
        # output
            depth_filename = os.path.join(
                out, os.path.splitext(os.path.basename(path))[0] + "_depth"
            )

            utils.write_depth(depth_filename, midas_prediction, bits=2)
            print('%gx%g Depth Done' % midas_prediction.shape[:2])

        print(f"Inferencing completed in {(time_after_inference - time_before_inference):.3f}s")
        print('Results saved to %s' % out)

    print('Done. (%.3fs)' % (time.time() - start_time))

if __name__ == '__main__':
    from utils.inference_options import parse_args
    options = parse_args()
    print(options)
    inference(options = options)


#!/user/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Howie'
def func1(x=2):
    '这是一个测试的函数，输入参数然后求平方值'
    y = x**10
    return y
a = func1(4)
b = func1()
print(a,b)
c = a + b
print(c)


# Prime Number Checker
# Author: Powell A. Mims
# This program checks if a number is prime or not

def is_prime(num):
    if num == 4:            # 4 / 2 = 2 --> range(2, 2) is empty. Skips
        return False;       # for loop and causes erroneous true return.
    max = int(num / 2);
    for i in range(2, max):
        if num % i == 0:
            return False;
    return True;

print("\nWelcome to the Prime Number Checker!\n");
number = input("What number should we check? ");

if not number.isnumeric():
    print("This program only works on integers.");
    exit();

number = int(number);
if is_prime(number):
    message = "";
else:
    message = " not";

print(f"This number is{message} prime.\n");


import tkinter as tk

def function(event):
    print(event.widget[button2 - button1])

root = tk.Tk()

button1 = tk.Button(root, text='1')
button1.pack()
button1.bind('<Button-1>', function)

button2 = tk.Button(root, text='2')
button2.pack()
button2.bind('<Button-1>', function)

root.mainloop()


import os.path
import shlex
import shutil
import struct
import subprocess
import sys
import tempfile
import numpy as np

# Constants
BH_TSNE_BIN_PATH = os.path.join(os.path.dirname(__file__), 'bh_tsne')
NOT_FOUND = 'Unable to find the bh_tsne binary in {}'.format(BH_TSNE_BIN_PATH)
# Default hyper-parameter values from van der Maaten (2013)
DEFAULT_PERPLEXITY = 30.0
DEFAULT_THETA = 0.5
###

class tSNE(object):
    """Mock Scikit manifold interface (at least the part needed)"""
    def __init__(self, n_components, theta=DEFAULT_THETA,
                 perplexity=DEFAULT_PERPLEXITY):
        """`theta` control approximation quality, 0 meaning exact algorithm"""
        self.n_components = n_components
        self.theta = float(theta)
        self.perplexity = float(perplexity)

    def fit_transform(self, data):
        return bh_tsne(data, self.perplexity, self.theta, self.n_components,
                       True)

class TmpDir(object):
    def __enter__(self):
        self._tmp_dir_path = tempfile.mkdtemp()
        return self._tmp_dir_path

    def __exit__(self, type, value, traceback):
        shutil.rmtree(self._tmp_dir_path)

def _read_unpack(fmt, fh):
    return struct.unpack(fmt, fh.read(struct.calcsize(fmt)))

def bh_tsne(samples, perplexity=DEFAULT_PERPLEXITY, theta=DEFAULT_THETA,
            out_dims=2, verbose=False):
    assert os.path.isfile(BH_TSNE_BIN_PATH), NOT_FOUND
    sample_count, sample_dim = samples.shape

    # bh_tsne works with fixed input and output paths, give it a temporary
    # directory to work in so we don't clutter the filesystem
    with TmpDir() as tmp_dir_path:
        # Note: The binary format used by bh_tsne is roughly the same as for
        # vanilla tsne
        with open(os.path.join(tmp_dir_path, 'data.dat'), 'wb') as data_file:
            # Write the bh_tsne header
            data_file.write(struct.pack('iidd', sample_count, sample_dim,
                                        theta, perplexity))
            # Then write the data
            for sample in samples:
                data_file.write(struct.pack('{}d'.format(len(sample)),
                                            *sample))

        if verbose:
            shutil.copy(os.path.join(tmp_dir_path, 'data.dat'),
                        '/users/lefag/illalla')
        # Call bh_tsne and let it do its thing
        with open('/dev/null', 'w') as dev_null:
            # bh_tsne is very noisy on stdout, tell it to use stderr if it is
            # to print any output
            output = sys.stdout if verbose else dev_null
            binary = os.path.abspath(BH_TSNE_BIN_PATH)
            args = shlex.split('{} {}'.format(binary, out_dims))
            try:
                subprocess.check_call(args, cwd=tmp_dir_path, stdout=output)
            except subprocess.CalledProcessError:
                if not verbose:
                    print('Enable verbose mode for more details')
                raise

        # Read and pass on the results
        with open(os.path.join(tmp_dir_path, 'result.dat'), 'rb') as output:
            # The first two integers are just the number of samples and the
            # dimensionality
            result_samples, result_dims = _read_unpack('ii', output)
            # Collect the results, but they may be out of order
            results = [_read_unpack('{}d'.format(result_dims), output)
                       for _ in xrange(result_samples)]
            # Now collect the landmark data so that we can return the data in
            # the order it arrived
            results = sorted([(_read_unpack('i', output), e)
                              for e in results])
            ordered = np.zeros((result_samples, result_dims))
            for idx, point in results:
                ordered[idx[0], :] = point
            return ordered
            # The last piece of data is the cost for each sample, we ignore it
            # read_unpack('{}d'.format(sample_count), output_file)

if __name__ == '__main__':
    data = np.array([[1.0, 0.0, 2.0], [0.0, 1.0, 2.5]])
    print(data)
    print(bh_tsne(data, out_dims=3, perplexity=0.1, verbose=True))


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

import traceback

from macdaily.core.brew import BrewCommand
from macdaily.util.compat import subprocess
from macdaily.util.const.string import MAX, MIN
from macdaily.util.tools.misc import date
from macdaily.util.tools.print import print_info, print_scpt, print_text
from macdaily.util.tools.script import run

class PostinstallCommand(BrewCommand):

    @property
    def cmd(self):
        return 'postinstall'

    @property
    def act(self):
        return ('postinstall', 'postinstalled', 'postinstalled')

    @property
    def job(self):
        return ('postinstallation', 'postinstallation')

    def _parse_args(self, namespace):
        self._endswith = namespace.get('endswith', MAX)  # pylint: disable=attribute-defined-outside-init
        self._no_cleanup = namespace.get('no_cleanup', False)  # pylint: disable=attribute-defined-outside-init
        self._startswith = namespace.get('startswith', MIN)  # pylint: disable=attribute-defined-outside-init

        self._all = namespace.get('all', False)  # pylint: disable=attribute-defined-outside-init
        self._quiet = namespace.get('quiet', False)  # pylint: disable=attribute-defined-outside-init
        self._verbose = namespace.get('verbose', False)  # pylint: disable=attribute-defined-outside-init
        self._yes = namespace.get('yes', False)  # pylint: disable=attribute-defined-outside-init

        self._logging_opts = namespace.get('logging', str()).split()  # pylint: disable=attribute-defined-outside-init
        self._postinstall_opts = namespace.get('postinstall', str()).split()  # pylint: disable=attribute-defined-outside-init

    def _run_proc(self):
        self._pkgs = list()
        self._fail = list()
        self._lost = list()
        for path in self._exec:
            text = f'Using {self.name} executable {path!r}'
            print_info(text, self._file, redirect=self._qflag)
            if self._proc_logging(path):
                self._proc_postinstall(path)
            else:
                text = f'No {self.desc[1]} to postinstall for executable {path!r}'
                print_info(text, self._file, redirect=self._qflag)
            self._proc_fixmissing(path)
        self._proc_cleanup()

    def _proc_logging(self, path):
        if self._packages:
            self._check_pkgs(path)
            self._did_you_mean()
        else:
            self._check_list(path)
        return self._check_confirm(path)

    def _check_list(self, path):
        text = f'Checking installed {self.desc[1]}'
        print_info(text, self._file, redirect=self._vflag)

        argv = [path, 'list']
        argv.extend(self._logging_opts)

        args = ' '.join(argv)
        print_scpt(args, self._file, redirect=self._vflag)
        with open(self._file, 'a') as file:
            file.write(f'Script started on {date()}\n')
            file.write(f'command: {args!r}\n')

        try:
            proc = subprocess.check_output(argv, stderr=subprocess.DEVNULL)
        except subprocess.SubprocessError:
            print_text(traceback.format_exc(), self._file, redirect=self._vflag)
            self._var__temp_pkgs = set()  # pylint: disable=attribute-defined-outside-init
        else:
            context = proc.decode()
            print_text(context, self._file, redirect=self._vflag)

            _temp_pkgs = list()
            for package in context.strip().split():
                if self._startswith <= package <= self._endswith:
                    _temp_pkgs.append(package)
            self._var__temp_pkgs = set(_temp_pkgs)  # pylint: disable=attribute-defined-outside-init
        finally:
            with open(self._file, 'a') as file:
                file.write(f'Script done on {date()}\n')

    def _proc_postinstall(self, path):
        text = f'Postinstalling specified {self.desc[1]}'
        print_info(text, self._file, redirect=self._qflag)

        argv = [path, 'postinstall']
        if self._quiet:
            argv.append('--quiet')
        if self._verbose:
            argv.append('--verbose')
        argv.extend(self._postinstall_opts)

        argv.append('')
        for package in self._var__temp_pkgs:
            argv[-1] = package
            print_scpt(' '.join(argv), self._file, redirect=self._qflag)
            if run(argv, self._file, timeout=self._timeout,
                   redirect=self._qflag, verbose=self._vflag):
                self._fail.append(package)
            else:
                self._pkgs.append(package)
        del self._var__temp_pkgs


# EXERCÍCIO 6.15
# Escreva um programa que guarde os pontos gerados pelo Programa 4.16 em um arquivo, um ponto por linha. Ao final, escreva nesse arquivo o resultado do cálculo para pi.

import math
import random

n_arquivo = 'pi.txt'
arquivo = open(n_arquivo, 'w')

def gera_coordenadas_aleatorias():
    ''' Gera par de coordenadas aleatórias.'''

    x = random.random()

    y = random.random()

    return x, y

def coordenadas_dentro_circulo(x, y):
    ''' Testa  se coordenadas estão dentro do círculo de raio 1.'''

    return math.hypot(x, y) < 1

def calcula_pi(n):
    ''' Calcula pi e o erro associado a partir de n pontos.'''

    conta_circulo = 0

    for i in range(n):

        x, y = gera_coordenadas_aleatorias()

        if coordenadas_dentro_circulo(x, y):

            conta_circulo += 1

    pi = 4 * conta_circulo / n

    erro = math.fabs(pi - math.pi)

    arquivo.write("\nPonto X:")
    arquivo.write(str(x))
    arquivo.write("\nPonto Y:")
    arquivo.write(str(y))
    arquivo.write("\nCom o Valor de pi sendo: ")
    arquivo.write(str(pi))

    return pi, erro

while True:
    num = int(input('Quantos pontos devem ser sorteados? (Digite 0 para sair): '))

    if num == 0:
        print("Programa encerrado.")
        break

    pi, erro = calcula_pi(num)
    print('Com', num, 'pontos, o valor de pi é', pi, 'com erro', erro)

Lista Arquivos e Strings/exercicio_6_15.py


import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("POPSMOKE SIMULATOR")

player = pygame.image.load('graphics/popSmoke.jpg').convert_alpha()

x = 250
y = 250
velocity = 10

#GAME LOOP
run = True
while run:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    userInput = pygame.key.get_pressed()

    if userInput[pygame.K_LEFT]:
        x -= velocity
        print('left')
    if userInput[pygame.K_RIGHT]:
        x += velocity
        print('right')
    if userInput[pygame.K_UP]:
        y -= velocity
        print('up')
    if userInput[pygame.K_DOWN]:
        y += velocity
        print('down')

    win.blit(player, (250, 250))

    pygame.display.update()


from anki import hooks
from anki.utils import ids2str

from aqt import browser
from aqt.qt import *
from aqt.utils import shortcut, showInfo

def fastRepositionOnSortChanged(self, idx, ord):
    isDueSort = self.model.activeCols[idx] == 'cardDue'
    self.form.mvtotopAction.setEnabled(isDueSort)
    self.form.mvuponeAction.setEnabled(isDueSort)
    self.form.mvdownoneAction.setEnabled(isDueSort)

def setupFastRepositionActions(browser):
    """Add actions to the browser menu to move the cards up and down
    """
    # Set the actions active only if the cards are sorted by due date. This is necessary because the reposition
    # is done considering the current ordering in the browser
    mvtotopAction = QAction(_("Move to top"), browser)
    mvtotopAction.setShortcut(shortcut(_("Alt+0")))
    mvtotopAction.triggered.connect(browser.moveCardToTop)

    mvuponeAction = QAction(_("Move one up"), browser)
    mvuponeAction.setShortcut(shortcut(_("Alt+Up")))
    mvuponeAction.triggered.connect(browser.moveCardUp)

    mvdownoneAction = QAction(_("Move one down"), browser)
    mvdownoneAction.setShortcut(shortcut(_("Alt+Down")))
    mvdownoneAction.triggered.connect(browser.moveCardDown)

    browser.form.mvtotopAction = mvtotopAction
    browser.form.mvuponeAction = mvuponeAction
    browser.form.mvdownoneAction = mvdownoneAction

    browser.form.menu_Cards.addSeparator()
    browser.form.menu_Cards.addAction(mvtotopAction)
    browser.form.menu_Cards.addAction(mvuponeAction)
    browser.form.menu_Cards.addAction(mvdownoneAction)

    isDueSort = browser.col.conf['sortType'] == 'cardDue'
    browser.form.mvtotopAction.setEnabled(isDueSort)
    browser.form.mvuponeAction.setEnabled(isDueSort)
    browser.form.mvdownoneAction.setEnabled(isDueSort)

def moveCard(self, pos):
    revs = self.col.conf['sortBackwards']
    srows = self.form.tableView.selectionModel().selectedRows()

    #Get only new cards and exit if none are selected
    cids = self.selectedCards()
    cids2 = self.col.db.list(
            "select id from cards where type = 0 and id in " + ids2str(cids))
    if not cids2:
        return showInfo(_("Only new cards can be repositioned."))

    #Get the list of indexes of the selcted rows
    srowsidxes = []
    for crow in srows:
        srowsidxes.append(crow.row())

    #Check if the first (last) selected row is the first (last) on the table
    #and return in that case because it cannot moved up (down)
    if pos == -1:
        srowidx = min(srowsidxes)
        if srowidx == 0:
            return
    elif pos == 1:
        srowidx = max(srowsidxes)
        if srowidx == len(self.model.cards)-1:
            return

    #Get the index of the card on which the new due is calculated
    startidx = srowidx+pos

    #Check that the card on which the new due is calculated is a new card, otherwise the selected
    #card is at the boundary with the review cards and should not be moved
    cf = [self.model.cards[startidx]]
    cf2 = self.col.db.list(
            "select id from cards where type = 0 and id in " + ids2str(cf))
    if not cf2:
        return

    #When we move down (up) and the cards are in ascending (descending) order, the new due date must be greater by one
    #respect the due date of the next (previous) card, otherwise the due date of the selected card will be equal of that of
    #the next (previous) card but its position will be still before the next (previous) card
    inc = (revs==0 and pos>0) or (revs==1 and pos<0)

    start=self.col.getCard(self.model.cards[startidx]).due+inc

    #Perform repositioning. Copied from browser.Browser repositon method. Should be updated is changed upstream
    self.model.beginReset()
    self.mw.checkpoint(_("Reposition"))
    self.col.sched.sortCards(cids, start=start, step=1, shuffle=0, shift=1) # Preserve this line like this
    self.search()
    self.mw.requireReset()
    self.model.endReset()
    #Update the due position of the next card added.
    #This guarantees that the new cards are added a the end.
    self.col.conf['nextPos'] = self.col.db.scalar(
            "select max(due)+1 from cards where type = 0") or 0

def moveCardUp(self):
    self.moveCard(-1)

def moveCardDown(self):
    self.moveCard(1)

def moveCardToTop(self):
    #Get only new cards and exit if none are selected
    cids = self.selectedCards()
    cids2 = self.col.db.list(
            "select id from cards where type = 0 and id in " + ids2str(cids))
    if not cids2:
        return showInfo(_("Only new cards can be repositioned."))

    #Perform repositioning. Copied from browser.Browser repositon method. Should be updated is changed upstream
    self.model.beginReset()
    self.mw.checkpoint(_("Reposition"))
    self.col.sched.sortCards(cids, start=0, step=1, shuffle=0, shift=1) # Preserve this line like this
    self.search()
    self.mw.requireReset()
    self.model.endReset()
    #Update the due position of the next card added.
    #This guarantees that the new cards are added a the end.
    self.col.conf['nextPos'] = self.col.db.scalar(
            "select max(due)+1 from cards where type = 0") or 0

browser.Browser.moveCard = moveCard
browser.Browser.moveCardUp = moveCardUp
browser.Browser.moveCardDown = moveCardDown
browser.Browser.moveCardToTop = moveCardToTop

browser.Browser.onSortChanged = hooks.wrap(
    browser.Browser.onSortChanged, fastRepositionOnSortChanged)

hooks.addHook("browser.setupMenus", setupFastRepositionActions)