import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import time
import os
import shutil
from datetime import datetime
from tqdm import tqdm
from load_data import load_data_imagefolder, load_hdf_data, load_split_data, load_fwa_data, load_split_data_random
from sklearn.metrics import confusion_matrix, roc_auc_score, classification_report
from transforms import (
    get_test_transform,
    train_albumentations,
    get_test_transform_albumentations,
)
import math
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from hp import hp

# Disable if input sizes vary a lot
torch.backends.cudnn.benchmark = True

if not os.path.exists(hp.save_folder):
    os.mkdir(hp.save_folder)

now = datetime.now()
writer = None
if not (hp.quick_run or hp.pre_run):
    writer = SummaryWriter(os.path.join("runs", hp.model_name, now.strftime("%d%b%I:%M%p")))

device = hp.device

# sorted
classes = ["fake", "real"]

def load_multi_gpu(model):
    model.to(device)
    if False or torch.cuda.device_count() > 1:
        print("Using", torch.cuda.device_count(), "GPUs!")
        # torch.distributed.init_process_group(backend="nccl")
        # model = nn.parallel.DistributedDataParallel(model)
        model = nn.DataParallel(model, hp.device_ids)
    else:
        print(r"Multiple GPU's not available (╯°□°）╯︵ ┻━┻")
    return model

def train_model(
    model, datasets, dataloaders, criterion, optimizer, scheduler, num_epochs, save_loc
):
    since = time.time()

    best_acc = 0.0

    for epoch in range(num_epochs):
        if hp.use_cos_anneal_restart:
            optimizer = optim.SGD(model.parameters(), **hp.sgd_params)
            scheduler = optim.lr_scheduler.CosineAnnealingLR(
                optimizer, T_max=len(dataloaders["train"]), **hp.cos_anneal_sched_params
            )
        print(f"Epoch {epoch + 1}/{num_epochs}")
        print("-" * 10)
        print("LR", optimizer.param_groups[0]["lr"])

        probabilites = torch.zeros(0, dtype=torch.float32, device="cpu")
        predictions = torch.zeros(0, dtype=torch.long, device="cpu")
        true_val = torch.zeros(0, dtype=torch.long, device="cpu")

        # Each epoch has a training and validation phase
        for phase in ["train", "test"]:
            n_iter_this_phase = 0
            if phase == "train":
                model.train()  # Set model to training mode
            else:
                if hp.quick_run:
                    break
                model.eval()  # Set model to evaluate mode

            running_loss = 0.0
            running_corrects = 0

            for inputs, labels in tqdm(dataloaders[phase], ncols=0, mininterval=1):
                if hp.quick_run and n_iter_this_phase >= 150:
                    break
                n_iter_this_phase += 1

                non_blocking_transfer = (
                    True if phase == "train" and hp.use_pinned_memory_train else False
                )
                inputs = inputs.to(device, non_blocking=non_blocking_transfer)
                labels = labels.to(device, non_blocking=non_blocking_transfer)

                optimizer.zero_grad()

                with torch.set_grad_enabled(phase == "train"):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)

                    loss = criterion(outputs, labels)

                    # backward + optimize only if in training phase
                    if phase == "train":
                        loss.backward()
                        optimizer.step()
                        if hp.use_one_cycle_lr or hp.use_cos_anneal_restart:
                            scheduler.step()
                    else:
                        # Softmax and calculate metrics
                        softmaxed = nn.functional.softmax(outputs, dim=1)
                        # Probability of class 1
                        probs = softmaxed[:, 1]
                        probabilites = torch.cat([probabilites, probs.view(-1).cpu()])
                        predictions = torch.cat([predictions, preds.view(-1).cpu()])
                        true_val = torch.cat([true_val, labels.view(-1).cpu()])

                # statistics
                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels.data)

            dataset_size = len(datasets[phase])
            epoch_loss = running_loss / dataset_size
            epoch_acc = float(running_corrects) / dataset_size
            if not hp.quick_run:
                writer.add_scalar(f"Loss/{phase}", epoch_loss, epoch)
                writer.add_scalar(f"Accuracy/{phase}", epoch_acc, epoch)

            print("{} Loss: {:.8f} Acc: {:.8f}".format(phase, epoch_loss, epoch_acc))

            if phase == "test":
                if hp.use_step_lr:
                    scheduler.step()
                elif hp.use_plateau_lr:
                    # Passing in test loss!
                    scheduler.step(epoch_loss)

            if phase == "test" and epoch_acc > best_acc:
                best_acc = epoch_acc
            if not hp.quick_run:
                file_name = f"{hp.model_name}_{epoch+1}.pt"
                torch.save(model.state_dict(), os.path.join(save_loc, file_name))
        if not hp.quick_run:
            true_val = true_val.numpy()
            predictions = predictions.numpy()
            probabilites = probabilites.numpy()
            print(classification_report(true_val, predictions, target_names=classes))
            writer.add_pr_curve("pr_curve", true_val, probabilites, epoch)
            print("Confusion Matrix")
            print(confusion_matrix(true_val, predictions))
            print()
            print("RoC AUC:")
            print(roc_auc_score(true_val, probabilites))
            print()
            probabilites = np.around(probabilites, decimals=1)
            hist, _ = np.histogram(probabilites, bins=3)
            print("# Predictions magnitude below 0.33", hist[0])
            print("# Predictions magnitude 0.33 to 0.66", hist[1])
            print("# Predictions magnitude above 0.66", hist[2])

    time_elapsed = time.time() - since
    print(
        "Training complete in {:.0f}m {:.0f}s".format(
            time_elapsed // 60, time_elapsed % 60
        )
    )
    print("Best val Acc: {:4f}".format(best_acc))

    # load best model weights
    return model

def load_data_for_model(model):
    image_size = model.get_image_size()
    mean, std = model.get_mean_std()
    train_data_transform = train_albumentations(image_size, mean, std)
    test_data_transform = get_test_transform_albumentations(image_size, mean, std)
    if hp.using_hdf:
        return load_hdf_data(hp.hdf_key)
    elif hp.using_split_random:
        return load_split_data_random(train_data_transform, test_data_transform)
    elif hp.using_split_cluster:
        return load_split_data(train_data_transform, test_data_transform)
    elif hp.using_fwa:
        return load_fwa_data(train_data_transform, test_data_transform)
    else:
        test_transform = get_test_transform(image_size, mean, std)
        data_transform = get_test_transform(image_size, mean, std)
        return load_data_imagefolder(
            train_data_transform=data_transform, test_data_transform=test_transform
        )

def pre_run():
    print("-------------------------------------")
    print(f"Now Pre-running model: {hp.model_name}")
    print("-------------------------------------")
    model = hp.model
    datasets, dataloaders = load_data_for_model(model)
    model = model.to(device)
    model = load_multi_gpu(model)
    weights = None
    if hp.use_class_weights:
        weights = torch.FloatTensor(hp.class_weights).to(device)
    criterion = nn.CrossEntropyLoss(weight=weights)

    # Find LR first
    logs, losses = find_lr(model, criterion, dataloaders["train"])
    torch.save(logs, "pre_run_logs.pt")
    torch.save(losses, "pre_run_losses.pt")
    # plt.plot(logs, losses)

def run():
    print("-------------------------------------")
    print(f"Now running model: {hp.model_name}")
    print(now.strftime("%A, %d %B at %I:%M %p"))
    print("-------------------------------------")

    save_loc = hp.model_name + now.strftime("%d%b%I:%M%p")
    save_loc = os.path.join(hp.save_folder, save_loc)
    if not hp.quick_run:
        if not os.path.isdir(save_loc):
            os.mkdir(save_loc)
        shutil.copy("hp.py", save_loc)
    model = hp.model
    datasets, dataloaders = load_data_for_model(model)

    print("Classes array (check order)")
    print(classes)

    model = model.to(device)
    model = load_multi_gpu(model)

    weights = None
    if hp.use_class_weights:
        weights = torch.FloatTensor(hp.class_weights).to(device)
    criterion = nn.CrossEntropyLoss(weight=weights)

    if hp.use_adamW:
        optimizer = optim.AdamW(model.parameters(), **hp.adamW_params)
    elif hp.use_sgd:
        optimizer = optim.SGD(model.parameters(), **hp.sgd_params)
    else:
        optimizer = None

    if hp.use_step_lr:
        scheduler = optim.lr_scheduler.StepLR(optimizer, **hp.step_sched_params)
    elif hp.use_plateau_lr:
        scheduler = optim.lr_scheduler.ReduceLROnPlateau(
            optimizer, **hp.plateau_lr_sched_params
        )
    elif hp.use_one_cycle_lr:
        scheduler = optim.lr_scheduler.OneCycleLR(
            optimizer, steps_per_epoch=len(dataloaders["train"]), **hp.oc_sched_params
        )
    else:
        scheduler = None

    model = train_model(
        model,
        datasets,
        dataloaders,
        criterion,
        optimizer,
        scheduler,
        hp.num_epochs,
        save_loc,
    )

def find_lr(net, criterion, trn_loader, init_value=1e-8, final_value=10.0, beta=0.98):
    """
    https://sgugger.github.io/how-do-you-find-a-good-learning-rate.html
    https://sgugger.github.io/the-1cycle-policy.html
    logs,losses = find_lr()
    plt.plot(logs,losses)
    For a OneCycleLR, The maximum should be the value picked with the Learning Rate Finder, and the lower one can be ten times lower.
    """
    if hp.use_adamW:
        optimizer = optim.AdamW(net.parameters(), **hp.adamW_params)
    elif hp.use_sgd:
        optimizer = optim.SGD(net.parameters(), **hp.sgd_params)
    num = len(trn_loader) - 1
    mult = (final_value / init_value) ** (1 / num)
    lr = init_value
    optimizer.param_groups[0]["lr"] = lr
    avg_loss = 0.0
    best_loss = 0.0
    batch_num = 0
    losses = []
    log_lrs = []
    for inputs, labels in tqdm(trn_loader, ncols=0, mininterval=1):
        batch_num += 1
        inputs = inputs.to(device, non_blocking=hp.use_pinned_memory_train)
        labels = labels.to(device, non_blocking=hp.use_pinned_memory_train)

        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, labels)

        # Compute the smoothed loss
        avg_loss = beta * avg_loss + (1 - beta) * loss.item()
        smoothed_loss = avg_loss / (1 - beta ** batch_num)

        # Stop if the loss is exploding
        if batch_num > 1 and smoothed_loss > 4 * best_loss:
            return log_lrs, losses

        # Record the best loss
        if smoothed_loss < best_loss or batch_num == 1:
            best_loss = smoothed_loss

        # Store the values
        losses.append(smoothed_loss)
        log_lrs.append(math.log10(lr))

        # Do the SGD step
        loss.backward()
        optimizer.step()

        # Update the lr for the next step
        lr *= mult
        optimizer.param_groups[0]["lr"] = lr
    return log_lrs[10:-5], losses[10:-5]

if __name__ == "__main__":
    if hp.pre_run:
        pre_run()
    else:
        run()
    writer.close()


# 수열정렬
n = int(input())
arr = list(map(int, input().split()))
visited = [0] * n;
list = sorted(arr)
for i in range(n):
    x = list.index(arr[i])
    print(x + visited[x], end=" ")
    visited[x] += 1

#회전하는 큐
from collections import deque
N, M = map(int, input().split())
queue = deque()
arr = deque(list(map(int, input().split())))
for i in range(N):
    queue.append(i + 1)
count = 0
while len(arr) > 0:
    x = arr.popleft()
    qLen = len(queue)
    i = queue.index(x)
    if i < qLen - i:
        k = 0
        while k < i:
            a = queue.popleft()
            queue.append(a)
            k += 1
            count += 1
    else:
        k = 0
        while k < qLen - i:
            a = queue.pop()
            queue.appendleft(a)
            k += 1
            count += 1
    if queue[0] == x:
        a = queue.popleft()
print(count)

#2338
a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b)

#1026
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort(reverse=True)
B.sort()
count = 0
for i in range(N):
    count += A[i] * B[i]
print(count)

#1003
T = int(input())
for i in range(T):
    N = int(input())
    a, b = 0, 1
    for j in range(2, N + 1):
        result = a + b
        a = b
        b = result
    if N == 0:
        print(b, a)
    else: print(a, b)

#1004
T = int(input())
for i in range(T):
    x1, y1, x2, y2 = map(int, input().split())
    n = int(input())
    count = 0
    for j in range(n):
        a, b, r = map(int, input().split())
        if ((x1 - a) * (x1 - a) + (y1 - b) *(y1 -b) > r * r) ^ ((x2 - a) * (x2 - a) + (y2 - b) *(y2 -b) > r * r):
            count += 1
    print(count)

#1057
n, a, b = map(int, input().split())
count = 0
while a != b:
    a -= a // 2
    b -= b // 2
    count += 1
print(count)

#1063
k, r, n = input().split()
kx, ky = ord(k[0]) - 64, int(k[1])
rx, ry = ord(r[0]) - 64, int(r[1])
n = int(n)
arr = ["R", "L", "B", "T", "RT", "LT", "RB", "LB"]
x = [1, -1, 0, 0, 1, -1, 1, -1]
y = [0, 0, -1, 1, 1, 1, -1, -1]
for i in range(n):
    move = input()
    pos = arr.index(move)
    nx, ny = kx + x[pos], ky + y[pos]
    if nx <= 0 or nx > 8 or ny <= 0 or ny > 8:
        continue
    elif nx == rx and ny == ry:
        nrx, nry = rx + x[pos], ry + y[pos]
        if nrx <= 0 or nrx > 8 or nry <= 0 or nry > 8 or nx <= 0 or nx > 8 or ny <= 0 or ny > 8:
            continue
        else:
            rx, ry = nrx, nry
            kx, ky = nx, ny
    else:
        kx, ky = nx, ny
print(chr(kx + 64) + str(ky))
print(chr(rx + 64) + str(ry))

#1072
import sys
input = sys.stdin.readline

x, y = map(int, input().split())
percent = y * 100 // x
if percent >= 99:
    print(-1)
else:
    left = 1
    right = x
    count = 0
    while left <= right:
        mid = (left + right) // 2
        if percent < ((y + mid) * 100 // x + mid):
            right = mid - 1
            count = mid
        else:
            left = mid + 1
print(count)

#1920
N = int(input())
arr = list(map(int, input().split()))
arr.sort()
M = int(input())
temp = list(map(int, input().split()))

for i in temp:
    left = 0
    right = N - 1
    isExist = False

    while left <= right:
        mid = (left + right) // 2
        if i == arr[mid]:
            isExist = True
            print(1)
            break
        else:
            if i > arr[mid]:
                left = mid + 1
            else:
                right = mid - 1
    if not isExist:
        print(0)

#2512
n = int(input())
arr = list(map(int, input().split()))
m = int(input())
left = 0
right = max(arr)
while left <= right:
    mid = (left + right) // 2
    count = 0
    for i in arr:
        if i >= mid:
            count += mid
        else:
            count += i
    if count <= m:
        left = mid + 1
    else:
        right = mid - 1

print(right)

#1463
N = int(input())
dp = [0] * (N + 1)
for i in range(2, N + 1):
    dp[i] = dp[i - 1] + 1
    if i % 2 == 0:
        dp[i] = min(dp[i], dp[i // 2] + 1)
    if i % 3 == 0:
        dp[i] = min(dp[i], dp[i // 3] + 1)
print(dp[N])

#1012
import sys
sys.setrecursionlimit(10000)
def dfs(x, y, n, m, arr):
    if 0 <= x < n and 0 <= y < m:
        if arr[x][y] == 1:
            arr[x][y] = 0
            dfs(x - 1, y, n, m, arr)
            dfs(x + 1, y, n, m, arr)
            dfs(x, y - 1, n, m ,arr)
            dfs(x, y + 1, n, m ,arr)
            return True
    return False

T = int(input())
for _ in range(T):
    result = 0
    m, n, k = map(int, input().split())
    arr = [[0] * m for _ in range(n)]

    for _ in range(k):
        y, x = map(int, input().split())
        arr[x][y] = 1
    for i in range(n):
        for j in range(m):
            if dfs(i, j, n, m, arr) == True:
                result += 1

    print(result)

#1166
# ========잘못된 풀이========
import math

n, l, w, h = map(int, input().split())
left = 0
right = math.gcd(l, w, h)
for _ in range(10000):
    mid = (left + right) / 2
    if (l // mid) * (w // mid) * (h / mid) >= n:
        left = mid
    else:
        right = mid
print("%.10f" %(right))

# ========옳은 풀이========
import sys

n, l, w, h = map(int, sys.stdin.readline().split())
left = 0
right = max(l, w, h)
for _ in range(10000):
    mid = (left + right) / 2
    if (l // mid) * (w // mid) * (h // mid) >= n:
        left = mid
    else:
        right = mid
print("%.10f" %(right))


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        if not root:
            return '#$'
        stack = [root]
        answer = ''
        while stack:
            node = stack.pop()
            if node:
                answer += '#' + str(node.val)
                stack.append(node.right)
                stack.append(node.left)
            else:
                answer += '#$'
        return answer

    def deserialize(self, data):
        data = data.split('#')[1:]
        if data[0] == '$':
            return None
        root = TreeNode(int(data[0]))
        data = data[::-1]
        data.pop()
        stack = [root]
        node = root
        while data:
            value = data.pop()
            while data and value != '$':
                node.left = TreeNode(int(value))
                node = node.left
                stack.append(node)
                value = data.pop()
            while data and value == '$':
                node = stack.pop()
                value = data.pop()
            if data:
                node.right = TreeNode(int(value))
                node = node.right
                stack.append(node)
        return root

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))


#!/usr/bin/python
# -*- coding: utf8 -*-

import json
import boto3
import time
import os

TABLE_NAME = os.getenv('dynamodb_table')
WEBSITE_BUCKET = os.getenv('bucket')

def update_json_file_to_s3():
    client = boto3.client('dynamodb')

    response = client.scan(
        TableName = TABLE_NAME,
        Select = 'SPECIFIC_ATTRIBUTES',
        ProjectionExpression = 'service, #r, #s',
        ExpressionAttributeNames = {
            "#r": "region",
            "#s": "status"
        }
    )
    flag = response.has_key('LastEvaluatedKey')
    items = response['Items']
    count = response['Count']

    while (flag):
        response = client.scan(
            TableName = TABLE_NAME,
            Select = 'SPECIFIC_ATTRIBUTES',
            ProjectionExpression = 'service, #r, #s',
            ExpressionAttributeNames = {
                "#r": "region",
                "#s": "status"
            },
            ExclusiveStartKey = response['LastEvaluatedKey']
        )

        items = items + response['Items']
        flag = response.has_key('LastEvaluatedKey')
        count += response['Count']

    response = {'Items': items, 'time': int(time.time()), 'Count': count}
    response_json = json.dumps(response, sort_keys=True, separators=(',', ': '))
    file = open('/tmp/data.json', 'w')
    file.write(response_json)
    file.close()

    s3 = boto3.resource('s3')
    s3.Bucket(WEBSITE_BUCKET).upload_file('/tmp/data.json', 'data/servicesStatus.json')

def lambda_handler(event, context):
    update_json_file_to_s3()

    return "Done."


import torch

import resnet_pytorch
import imbalanced_dataset
import numpy as np
import utils
import argparse
from itertools import chain
import os
try:
    from apex import amp
except ImportError:
    amp = None
import train
import initialise_model

def main(args):
    dset_name = args.dset_name
    train_dir = os.path.join(args.data_path, "train")
    val_dir = os.path.join(args.data_path, "val")
    dataset, dataset_test, _, test_sampler = train.load_data(train_dir, val_dir, args)

    num_classes = len(dataset.cls_num_list)

    data_loader_test = torch.utils.data.DataLoader(
        dataset_test, batch_size=args.batch_size,
        sampler=test_sampler, num_workers=args.workers, pin_memory=True)

    model = initialise_model.get_model(args,num_classes)
    criterion = initialise_model.get_criterion(args,dataset)
    checkpoint = torch.load(args.load_from, map_location='cpu')
    model.load_state_dict(checkpoint['model'])

    model.to('cuda')
    if args.apex:
        optimizer = torch.optim.SGD(
            model.parameters(), lr=0.01, momentum=0.0, weight_decay=0.0)
        model, optimizer = amp.initialize(model, optimizer,
                                          opt_level=args.apex_opt_level
                                          )

    avg_acc,preds,targets=evaluate(model.cuda(), data_loader_test, device='cuda',criterion=criterion)

    print(f'Avg Acc is: {avg_acc}')

    f,c,r = shot_acc(np.array(preds),np.array(targets),dataset.targets)

    print(f'Many shot Acc is: {f}, median shot Acc is: {c}, low shot Acc is: {r}')

    return 0

def shot_acc (preds, labels, train_targets, many_shot_thr=100, low_shot_thr=20, acc_per_cls=False):

    if isinstance(train_targets, np.ndarray):
        training_labels = np.array(train_targets).astype(int)
    else:
        training_labels = np.array(train_targets).astype(int)

    if isinstance(preds, torch.Tensor):
        preds = preds.detach().cpu().numpy()
        labels = labels.detach().cpu().numpy()
    elif isinstance(preds, np.ndarray):
        pass
    else:
        raise TypeError('Type ({}) of preds not supported'.format(type(preds)))
    train_class_count = []
    test_class_count = []
    class_correct = []
    for l in np.unique(labels):
        train_class_count.append(len(training_labels[training_labels == l]))
        test_class_count.append(len(labels[labels == l]))
        class_correct.append((preds[labels == l] == labels[labels == l]).sum())

    many_shot = []
    median_shot = []
    low_shot = []
    for i in range(len(train_class_count)):
        if train_class_count[i] > many_shot_thr:
            many_shot.append((class_correct[i] / test_class_count[i]))
        elif train_class_count[i] < low_shot_thr:
            low_shot.append((class_correct[i] / test_class_count[i]))
        else:
            median_shot.append((class_correct[i] / test_class_count[i]))

    if len(many_shot) == 0:
        many_shot.append(0)
    if len(median_shot) == 0:
        median_shot.append(0)
    if len(low_shot) == 0:
        low_shot.append(0)

    if acc_per_cls:
        class_accs = [c / cnt for c, cnt in zip(class_correct, test_class_count)]
        return np.mean(many_shot), np.mean(median_shot), np.mean(low_shot), class_accs
    else:
        return np.mean(many_shot), np.mean(median_shot), np.mean(low_shot)

def evaluate(model, data_loader, device, print_freq=10,criterion=None):
    model.eval()
    metric_logger = utils.MetricLogger(delimiter="  ")
    header = 'Test:'
    predictions=[]
    targets=[]
    with torch.no_grad():
        for image, target in metric_logger.log_every(data_loader, print_freq, header):
            image = image.to(device, non_blocking=True)
            target = target.to(device, non_blocking=True)
            output = model(image)
            if hasattr(criterion, 'iif'):
                output=criterion(output,infer=True)
            acc1, acc5 = utils.accuracy(output, target, topk=(1, 5))

            predictions=list(chain(predictions,output.argmax(axis=1).tolist()))
            targets=list(chain(targets,target.tolist()))

            # FIXME need to take into account that the datasets
            # could have been padded in distributed setup
            batch_size = image.shape[0]
#             metric_logger.update(loss=loss.item())
            metric_logger.meters['acc1'].update(acc1.item(), n=batch_size)
            metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
    # gather the stats from all processes
    metric_logger.synchronize_between_processes()

    print(' * Acc@1 {top1.global_avg:.3f} Acc@5 {top5.global_avg:.3f}'
          .format(top1=metric_logger.acc1, top5=metric_logger.acc5))

    return metric_logger.acc1.global_avg,predictions,targets

def get_args_parser():
    parser = argparse.ArgumentParser(description='Parse arguments for per shot acc.')
    parser.add_argument('--distributed', default=False)
    parser.add_argument('--dset_name', default='imagenet_lt',type=str, help='Dataset Name imagenet_lt|places')
    parser.add_argument(
        '--data-path', default='../../../datasets/ILSVRC/Data/CLS-LOC/', help='dataset')
    parser.add_argument("--auto-augment", default=None, type=str, help="auto augment policy (default: None)")
    parser.add_argument("--ra-magnitude", default=9, type=int, help="magnitude of auto augment policy")
    parser.add_argument("--augmix-severity", default=3, type=int, help="severity of augmix policy")
    parser.add_argument("--random-erase", default=0.0, type=float, help="random erasing probability (default: 0.0)")
    parser.add_argument('--sampler', default='random', type=str, help='sampling, [random,upsampling,downsampling]')
    parser.add_argument('--iif', default='raw',type=str, help='Type of IIF variant')
    parser.add_argument('--classif', default='ce',type=str, help='Type of classification')
    parser.add_argument('--classif_norm', default=None,type=str, help='Type of classifier Normalisation {None,norm,cosine')
    parser.add_argument('--load_from', default='', help='load wweights only from checkpoint')
    parser.add_argument('-j', '--workers', default=4, type=int, metavar='N',help='number of data loading workers (default: 16)')
    parser.add_argument('-b', '--batch-size', default=256, type=int)
    parser.add_argument('--model', default='resnet50', help='model, E.g.(se_resnext50_32x4d)')
    parser.add_argument('--use_gumbel_se', default=False, help='Gumbel activation in excitation phase of SE',action='store_true')
    parser.add_argument('--use_gumbel_cb', default=False, help='Gumbel activation in spatial gate phase of CB',action='store_true')

    parser.add_argument('--criterion', default='ce',type=str, help='Criterion used for classifier {ce,bce,gce')

    parser.add_argument('--apex', action='store_true',
                        help='Use apex for mixed precision training')
    parser.add_argument(
        "--interpolation", default="bilinear", type=str, help="the interpolation method (default: bilinear)"
    )
    parser.add_argument(
        "--val-resize-size", default=256, type=int, help="the resize size used for validation (default: 256)"
    )
    parser.add_argument(
        "--val-crop-size", default=224, type=int, help="the central crop size used for validation (default: 224)"
    )
    parser.add_argument(
        "--train-crop-size", default=224, type=int, help="the random crop size used for training (default: 224)"
    )
    parser.add_argument(
        "--label-smoothing", default=0.0, type=float, help="label smoothing (default: 0.0)", dest="label_smoothing"
    )
    parser.add_argument('--apex-opt-level', default='O2', type=str,
                        help='For apex mixed precision training'
                             'O0 for FP32 training, O1 for mixed precision training.'
                             'For further detail, see https://github.com/NVIDIA/apex/tree/master/examples/imagenet'
                        )
    parser.add_argument(
        "--cache-dataset",
        dest="cache_dataset",
        help="Cache the datasets for quicker initialization. It also serializes the transforms",
        action="store_true",
    )
    parser.add_argument(
        "--deffered",
        help="Use deferred schedule",
        action="store_true",
    )
    parser.add_argument(
        "--pretrained",
        dest="pretrained",
        help="Use pre-trained models from the modelzoo or local --> [pytorch, path-to-model]",
        default=None, type=str,
    )
    parser.add_argument("--weights", default=None, type=str, help="Dummy input, do not change")
    parser.add_argument('--reduction', default='mean', type=str, help='reduce mini batch')
    parser.add_argument(
        "--test-only",
        dest="test_only",
        help="Dummy input, do not change",
        action="store_true",
    )

    return parser

if __name__ == "__main__":
    args = get_args_parser().parse_args()
    main(args)
    print('end of program')


import numpy as np
import random

class Tube:
    def __init__(self):
        """ Initializes a clean tube

        the length parameter specifies the dimensions
        of the field, It is passed to the class to ensure
        that the randomly generated tubes have a center pt
        inside the bounds of the field.

        regardless of slope point P is always on left side.
        P(x,y) 0----------------0 Q(x,y)
        """
        self._m = None
        self._l = None
        self._b = None
        self._theta = None
        self._neighbors = {}
        self._cm = [] #[Xcm,Ycm]
        self._P = [] #[Xp,Yp]
        self._Q = [] #[Xq,Yq]

    def createLine(self,slope,center):
        """ Generates a Line segment

        This function generates the initial line segment, It also
        modifies the variables that are based on slope and center
        point after each iteration.
        """

        if self._l == None:
            self._l = random.uniform(2,5)
        self._m = slope
        self._cm = center
        self._neighbors = {}
        self._theta = np.arctan(self._m)
        self._b = self._cm[1] - self._m*self._cm[0]

        xmax = self._cm[0] + abs((self._l*np.cos(self._theta)))
        xmin = self._cm[0] - abs((self._l*np.cos(self._theta)))
        ymax = self._cm[1] + abs((self._l*np.sin(self._theta)))
        ymin = self._cm[1] - abs((self._l*np.sin(self._theta)))
        if self._m <= 0:
            self._P = [xmin,ymax]
            self._Q = [xmax,ymin]
        else:
            self._P = [xmin,ymin]
            self._Q = [xmax,ymax]

        return None

    def addNeighbors(self, key, angle, x_intercept):
        """ Function for adding neighbors

        The Field class keeps track of the intersecting
        tubes via a dict'd list. {key:[angle,x_intecept]}
        """
        self._neighbors[key] = list()
        self._neighbors[key] = [angle,x_intercept]

        return None

    def getParams(self):
        """ A function that returns requested parameters.

        This function takes all of the individual tube
        attributes, and returns them as a dict.
        """

        params = {'m':self._m,'l':self._l,'b':self._b,'cm':self._cm,'theta':self._theta,'P':self._P,'Q':self._Q,'neighbors':self._neighbors}

        return params


#Crea una función llamada contar_vocales que tome una cadena de texto como parámetro y
#devuelva el número de vocales que contiene.

def contar_vocales(cadena):
    conteo_vocales = 0
    for letra in cadena:
        if letra.upper() in "AEIOU":
            conteo_vocales += 1
    return conteo_vocales

cadena = str(input("Ingrese cadena de texto para conocer las vocales que contiene: "))
cantidad_vocales = contar_vocales(cadena)
print(f"La cadena tiene una totalidad de {cantidad_vocales} vocales")


from model.detection import detection
from model.detection.lossFuntion import loss_region
import cv2
import os
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow.keras.backend as K
import numpy as np

enco_path = "data/image/resized"
original_file_list = os.listdir(enco_path)
num_enco_files = len(original_file_list)

deco_path = "data/image/hitmap"
heatmap_file_list = os.listdir(deco_path)
num_deco_f = len(heatmap_file_list)

X = None
Y = None

for i in range(num_enco_files):
    img_path = enco_path + "/after_" + str(i) + ".jpg"
    print(img_path)
    img = cv2.imread(img_path)
    img = tf.image.convert_image_dtype(img, tf.float32)
    img = np.reshape(img, ((1,) + img.shape))  # 차원추가
    if i == 0:
        X = img
    else:
        X = np.concatenate((X, img), axis=0)  # 추가된 차원(4차원) 방향으로 이미지 연결

for i in range(num_deco_f):
    img_path = deco_path + "/heatmap_" + str(i) + ".jpg"
    print(img_path)
    img = cv2.imread(img_path)
    img = tf.image.convert_image_dtype(img, tf.float32)
    img = np.reshape(img, ((1,) + img.shape))  # 차원추가
    if i == 0:
        Y = img
    else:
        Y = np.concatenate((Y, img), axis=0)  # 추가된 차원(4차원) 방향으로 이미지 연결

print("model 생성시작...")
# model
model = detection.Detection_model()
model.summary()
print("model 생성완료")

# callback
callbacks_list = [
    EarlyStopping(
        monitor="val_acc",
        patience=1,
    ),
    ModelCheckpoint(
        filepath="model.hr",  # 모델파일 경로,
        monitor="val_loss",
        save_best_only=True,
    ),
]

# compile
model.compile(optimizer="adam", loss=loss_region, metrics=["accuracy"])  # acc

print("model 학습 시작...")

# fit
model.fit(X, Y, batch_size=1, epochs=1, verbose=True, callbacks=callbacks_list)

print("model 학습 종료")


import json
import glob
import os
from dashify.visualization.data_model.grid_search_result import GridSearchResult
from dashify.visualization.data_model.experiment import Experiment
from typing import Dict, List

class LocalDataLoader:
    """
    Static class that loads the experiments of a given grid search from disk
    and creates a `GridSearchResult` object.
    """

    @staticmethod
    def get_grid_search_results(gs_log_dir: str) -> GridSearchResult:
        """
        Creates a `GridSearchResult` from a given logging directory.
        :param gs_log_dir: Path to grid search logs
        :return: GridSearchResult
        """
        gs_result = GridSearchResult(gs_log_dir)
        config_paths = glob.glob(os.path.join(gs_log_dir, "**/config.json"), recursive=True)
        metric_paths = glob.glob(os.path.join(gs_log_dir, "**/metrics.json"), recursive=True)

        LocalDataLoader._check_integrity_of_logs(config_paths, metric_paths)

        # load configs and metrics into dictionaries (experiment_id -> loaded_resource)
        configs = {LocalDataLoader._resource_path_to_experiment_id(config_path, gs_log_dir): LocalDataLoader._load_file(resource_path=config_path)
                   for config_path in config_paths}
        metrics = {LocalDataLoader._resource_path_to_experiment_id(metric_path, gs_log_dir): LocalDataLoader._load_file(resource_path=metric_path)
                   for metric_path in metric_paths}

        # create experiment and store in grid search result object
        for experiment_id in configs.keys():
            experiment = Experiment(config=configs[experiment_id],
                                    metrics=metrics[experiment_id],
                                    identifier=experiment_id)
            gs_result.add_experiment(experiment)
        return gs_result

    @staticmethod
    def _check_integrity_of_logs(config_paths: List[str], metric_paths: List[str]):
        """
        Makes sure that each experiment has all files present.
        :param config_paths: List of config file paths
        :param metric_paths: List of metric file paths
        :return:
        """
        experiments_configs = [os.path.dirname(c) for c in config_paths]
        experiments_metrics = [os.path.dirname(m) for m in metric_paths]
        intersection = [e for e in experiments_metrics if e in experiments_configs]
        if len(intersection) != len(experiments_configs) or len(intersection) != len(experiments_metrics):
            raise Exception("Dataset corrupt!!!")

    @staticmethod
    def _load_file(resource_path: str):
        with open(resource_path, "r") as f:
            return json.load(f)

    @staticmethod
    def _resource_path_to_experiment_id(experiment_file_path: str, gs_log_dir: str) -> str:
        """
        Maps the file path of a config or metrics file to the respective experiment id.
        :param experiment_file_path:
        :param gs_log_dir:
        :return:
        """
        return os.path.dirname(os.path.relpath(experiment_file_path, gs_log_dir))


import torch
from torch import nn
from d2l import torch as d2l

class BatchNorm(nn.Module):
    def __init__(self, num_features, num_dims):
        """
        num_features: nums of outputs for fc
                      nums of output channels for convolution
        num_dims: 2 for fc,
                  4 for conv
        """
        super().__init__()
        if num_dims == 2:
            shape = (1, num_features)
        else:
            shape = (1, num_features, 1, 1)
        # 参数赋形初始化
        self.gamma = nn.Parameter(torch.ones(shape))
        self.beta = nn.Parameter(torch.zeros(shape))
        self.moving_mean = torch.zeros(shape)
        self.moving_var = torch.zeros(shape)

    def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum):
        # 推理模式
        if not torch.is_grad_enabled():
            X_hat = (X - moving_mean) / torch.sqrt(moving_var + eps)
        # 训练模式
        else:
            assert len(X.shape) in (2, 4)
            # 当X为全连接层上的小批量，对小批量N的一维样本求均值和方差
            if len(X.shape) == 2:
                mean = X.mean(dim=0, keepdim=True) # shape = (1, X.shape[1])
                var = ((X - mean)**2).mean(dim=0, keepdim=True)
            # 当X为卷积层上的小批量，对小批量N的每一个通道求HxW的均值和方差
            else:
                mean = X.mean(dim=(0,2,3), keepdim=True) # shape = (1, C, 1, 1)
                var = ((X - mean)**2).mean(dim=(0,2,3), keepdim=True)
            # 归一化
            X_hat = (X - mean) / torch.sqrt(var + eps)
            # 持续更新所有样本的均值和方差，为推理阶段的BN准备
            moving_mean = momentum * moving_mean + (1.0 - momentum) * mean
            moving_var = momentum * moving_var + (1.0 - momentum) * var
        # 可训练的伸缩参数和偏移参数，输出最终的BN结果
        Y = gamma * X_hat + beta
        return Y, moving_mean, moving_var

    def forward(self, X):
        if self.moving_mean.device != X.device:
            self.moving_mean = self.moving_mean.to(X.device)
            self.moving_var = self.moving_var.to(X.device)

        Y, self.moving_mean, self.moving_var = batch_norm(X, self.gamma, self.beta,
                                                          self.moving_mean, self.moving_var,
                                                          eps=1e-5, momentum=0.9)
        return Y

# 应用`BatchNorm`于LeNet模型
net = nn.Sequential(nn.Conv2d(1, 6, kernel_size=5),
                    BatchNorm(num_features=6, num_dims=4),
                    nn.Sigmoid(),
                    nn.MaxPool2d(kernel_size=2, stride=2),
                    nn.Conv2d(6, 16, kernel_size=5),
                    BatchNorm(num_features=16, num_dims=4),
                    nn.Sigmoid(),
                    nn.MaxPool2d(kernel_size=2, stride=2),
                    nn.Flatten(),
                    nn.Linear(16 * 4 * 4, 120),
                    BatchNorm(num_features=120, num_dims=2),
                    nn.Sigmoid(),
                    nn.Linear(120, 84),
                    BatchNorm(num_features=84, num_dims=2),
                    nn.Sigmoid(),
                    nn.Linear(84, 10))

# 在Fashion-MNIST数据集上训练网络
lr, num_epochs, batch_size = 1.0, 10, 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())


'''
Script: Image to sketch.
Author@ mujeebishaque
'''

import argparse
import cv2, os

class SketchImage():

    @staticmethod
    def sketch(image_path, destination):
        if not image_path or len(image_path) < 6:
            raise Exception("Check the image path provided.")
        if not destination or len(destination) < 2:
            print("\nINFO: No destination directory provided. Sketch would be saved in the current directory.")

        filename = str(image_path).split(os.sep)[-1]
        _filename, tail = filename.split('.')

        _image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

        invert = cv2.bitwise_not(_image)  # helps in masking of the image
        blur = cv2.GaussianBlur(invert, (21, 21), 0)
        invertedblur = cv2.bitwise_not(blur)
        sketch = cv2.divide(_image, invertedblur, scale=256.0)

        try:
            cv2.imwrite(_filename+'_gray.'+tail, sketch)  # converted image is saved as mentioned name
        except Exception:
            raise Exception("Can't write data to the folder.")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='''
    This script takes in image path and converts the image into sketch and
    outputs to it either in the provided directory or in the current directory where this script is being executed.''', epilog="pythonvoyage.com")

    parser.add_argument('-i', '--image', required=True, type=str, help='Image path input like C:/windows/Dell/Desktop/demo.png')
    parser.add_argument('-o', '--output', required=False, type=str, help='Output path like C:/windows/Dell/Desktop/Output/image.png')

    argument = vars(parser.parse_args())

    image_path  = argument['image']
    output_path = argument['output']
    try:
        SketchImage.sketch(image_path, output_path)
    except IOError:
        raise Exception("Can't sketchify provided image.")


import requests
import json

BASE_URL = 'localhost:9091/'

print("\n")
#일반 get request
response = requests.get(BASE_URL + 'userList/v1.0')
data = response.json()
print("1. 유저리스트 조회 : ", data['check'])

#일반 post request에 params 세팅 후 전송
params = {'key1' : 'value1',
          'key2' : 'value2'}
response = requests.post(BASE_URL + 'userInfo/v1.0/post', params)
data = response.json()
print("2. 유저정보 업데이트 is : ", data['check'])

#PUT 헤더와 파라미터 세팅
header = {
    "accept" : "application/json",
    "Content-Type" : "application/json;charset=UTF-8"
}
params = {'key1' : 'value1',
          'key2' : 'value2'}
response = requests.put(BASE_URL + 'userInfo/v1.0/put', headers = header, data = json.dumps(params))
data = response.json()
print("3. 유저정보 저장 is : ", data['check'])

#GET 요청 파라미터 추가 타입
response = requests.get(BASE_URL + 'userDetail/v1.0/get/' + str(userList['response'][0]['userSeq']))
data = response.json()
print("4. 유저상세조회 is : ", data['check'])

#GET 요청 파라미터 세팅 타입
params = {'key1' : 'value1',
          'key2' : 'value2'}
response = requests.get(BASE_URL + 'stock/v1.0/list', params=params)
data = response.json()
print("5. 유저특성조회 is : ", data['check'])


'''You're given a list of integers nums . Write a function that returns a boolean representing whether there
exists a zero-sum subarray of nums .
A zero-sum subarray is any subarray where all of the values add up to zero. A subarray is any contiguous
section of the array. For the purposes of this problem, a subarray can be as small as one element and as
long as the original array.

Sample Input
nums = [-5, -5, 2, 3, -2]

Sample Output
True // The subarray [-5, 2, 3] has a sum of 0'''

def zeroSumSubarray(nums):
    # Write your code here.
    n_sum = set()
    sum = 0
    for i in nums:
        sum += i
        # if sum is repeated, that means previous subarray totals to zero
        if sum == 0 or sum in n_sum:
            return True
        n_sum.add(sum)
    return False


from bs4 import BeautifulSoup
import fileinput
import html2text
import json
import logging
import markdown
import random
import requests
import shutil
import sys

# Load json in memory
def get_challenge_updates(file_path: str, update_field: str) -> list:
    # open with utf 8 encoding

    with open(file_path, 'r') as file:
        data = json.load(file)

    temp = list()
    for i in data[update_field]:
        temp.append(i)

    file.close()
    print("⚙Updating challenges...")
    return temp

# Choose a random challenge
def select_daily_challenge(file: str, upcoming_list: list, old_list: list) -> str:
    daily_challenge = random.choice(upcoming_list)
    if len(old_list) >= len(upcoming_list):
        old_list = []
        update_challenges_list(file, old_list)
        daily_challenge = random.choice(upcoming_list)
        print("🌟 " + daily_challenge)
        return daily_challenge

    while is_in_old(daily_challenge, old_list):
        print("Oops! Already taken 🎯")
        daily_challenge = random.choice(upcoming_list)

    old_list.append(daily_challenge)
    update_challenges_list(file, old_list)
    print("🌟 " + daily_challenge)
    return daily_challenge

def is_in_old(i: str, old_list: list) -> bool:
    return i in old_list

# === Complementary method
def update_challenges_list(file, new_old: list):
    with open(file, "r+", encoding="utf-8") as json_file:
        data = json.load(json_file)
        data['old'] = new_old

        json_file.seek(0)  # rewind
        json.dump(data, json_file, indent=2)
        json_file.truncate()
        print("Old list update: ⏬")
        print(new_old)

# Get today's challenge title and content
def get_challenge_content(file: str, challenge: str) -> str:
    with open(file, "r+") as json_file:
        data = json.load(json_file)

        for i in data['challenges']:
            name = i['title']
            if name == challenge:
                content = i['content']
                print("👀 " + content)
                return content

# Get last challenge
def get_last_challenge(file: str) -> str:
    file = open(file, "rb")
    data = json.load(file)
    last = data['last_problem_title']
    print("👴 Latest challenge: " + last)
    file.close()
    return last

def set_last_challenge(file, challenge):
    with open(file, "r+") as json_file:
        data = json.load(json_file)
        data['last_problem_title'] = challenge
        json_file.seek(0)
        json.dump(data, json_file)
        json_file.truncate()
        print("✅ Last challenge updated: " + challenge)
    json_file.close()

def set_last_challenge_content(file: str, today_challenge_content: str):
    with open(file, "r+", encoding="utf-8") as json_file:
        data = json.load(json_file)
        data['last_problem_content'] = today_challenge_content
        json_file.seek(0)
        json.dump(data, json_file)
        json_file.truncate()
        print("✅ Last challenge content updated: " + str(today_challenge_content))
    json_file.close()

# Write today's challenge and solution
def write_challenge_of_the_day(readme_file: str, new_text: str, placeholder):
    # write to markdown
    for line in fileinput.input(readme_file, inplace=True, encoding="utf-8"):
        if placeholder in line:
            line = line.replace(placeholder, new_text)
        sys.stdout.write(line)

def write_solution(solution, lang):
    pass

def main():
    # Make a GET request to the problem page
    url: str = "https://leetcode.com/problems/all/"
    page = requests.get(url)

    # Parse the HTML of the page
    soup = BeautifulSoup(page.content, "html.parser")

    # Find the title and description elements
    title_element = soup.find("h4", class_="title")
    description_element = soup.find("div", class_="question-content")

    # Extract the text from the elements
    title = title_element
    description = description_element

    # Save the information to a JSON file
    data = {
        "title": title,
        "description": description
    }
    with open("problem.json", "w") as f:
        json.dump(data, f)

# -------------
def read_file(file_name: str):
    logging.info("📰Reading file...")
    with open(file_name, "r+", encoding="utf-8") as file:
        text = file.read()
        return str(text)

def save_text_to_html(text):
    html = markdown.markdown(text)
    with open("scripts/readme.html", "w", encoding="utf-8") as file:
        file.write(html)

def replace_text_in_html(class_name: str, tag: str, new_text: str):
    with open("scripts/readme.html", "r+", encoding="utf-8") as file:
        html_text = file.read()
        soup = BeautifulSoup(html_text, features="html.parser")
        element = soup.find(tag, {"class": class_name})
        print("🔎 Tag found")
        print(element.string)
        element.string = new_text

        file.seek(0)
        file.write(soup.prettify())
        file.truncate()
        print("✅ Text replaced in html")

def convert_html_to_markdown(html):
    markdown_text = html2text.html2text(html)
    with open("README.md", "w+", encoding="utf-8") as file:
        file.write(markdown_text)

def copyfile(file_to_copy, new_path):
    shutil.copyfile(file_to_copy, new_path)

if __name__ == '__main__':
    # Variables
    challenges_json = "scripts/challenges.json"

    # TODO: Convert the current README into HTML daily

    # Load lists in memory
    upcoming = get_challenge_updates(challenges_json, "upcoming")
    old = get_challenge_updates(challenges_json, "old")

    # Choose a random challenge ⬇
    # Challenge Name
    daily = select_daily_challenge(challenges_json, upcoming, old)

    # Challenge Content
    daily_content = get_challenge_content(challenges_json, daily)

    # Pull the HTML temp file and replace the text
    replace_text_in_html("problem-title", "h3", daily)
    replace_text_in_html("problem-content", "p", daily_content)
    replace_text_in_html("problem-solution", "pre", "🤓")

    # Convert it back to markdown
    convert_html_to_markdown(read_file("scripts/readme.html"))

    # Copy the README to the root folder to replace it
    copyfile("scripts/readme.md", "../README.md")

    logging.info('Done!')


import oneflow as flow
import oneflow.nn as nn
import oneflow.distribute as distribute_util

def meanshift(x, rgb_range, rgb_mean, rgb_std, sign=-1, name="Meanshift"):
    # Concat the rgb_std
    _new_constant_std_0 = flow.constant_scalar(rgb_std[0], dtype=flow.float32, name=name + "_std_0")
    _new_constant_std_1 = flow.constant_scalar(rgb_std[1], dtype=flow.float32, name=name + "_std_1")
    _new_constant_std_2 = flow.constant_scalar(rgb_std[2], dtype=flow.float32, name=name + "_std_2")
    _std = flow.concat(
        inputs=[_new_constant_std_0, _new_constant_std_1, _new_constant_std_2],
        axis=0,
    )

    _reshaped_std = flow.reshape(_std, (3, 1, 1, 1), name=name + "reshape_std")

    # Concat the rgb_mean
    _new_constant_mean_0 = flow.constant_scalar(rgb_mean[0], dtype=flow.float32, name=name + "_mean_0")
    _new_constant_mean_1 = flow.constant_scalar(rgb_mean[1], dtype=flow.float32, name=name + "_mean_1")
    _new_constant_mean_2 = flow.constant_scalar(rgb_mean[2], dtype=flow.float32, name=name + "_mean_2")

    _mean = flow.concat(
        inputs=[_new_constant_mean_0, _new_constant_mean_1, _new_constant_mean_2],
        axis=0,
    )

    _weight_ones = flow.constant(1.0, dtype=flow.float32, shape=(3, 3), name=name + "_ones")

    # Generate eye matrix

    # [[1, 0, 0],    [[0, 0, 0],
    #  [1, 1, 0], -   [1, 0, 0],
    #  [1, 1, 1]]     [1, 1, 0]]

    weight = flow.math.tril(_weight_ones, 0) - flow.math.tril(_weight_ones, -1)
    weight = flow.reshape(weight, shape=(3, 3, 1, 1), name=name + "_reshaped_weight")
    weight = flow.math.divide(weight, _reshaped_std)

    bias = sign * rgb_range * _mean
    bias = flow.math.divide(bias, _std)

    _conv = flow.nn.conv2d(x, filters=weight, strides=1, padding="SAME", name=name + "_mean_shift_conv")
    output = flow.nn.bias_add(_conv, bias, data_format="NCHW", name=name + "_addbias")
    return output

def _batch_norm(inputs, name, trainable=True, training=True):
    params_shape = [inputs.shape[1]]
    # Float32 required to avoid precision-loss when using fp16 input/output
    params_dtype = flow.float32 if inputs.dtype == flow.float16 else inputs.dtype
    if not flow.current_global_function_desc().IsTrainable() or not trainable:
        training = False
    with flow.scope.namespace(name):
        beta = flow.get_variable(
            name="beta",
            shape=params_shape,
            dtype=params_dtype,
            initializer=flow.zeros_initializer(),
            trainable=trainable,
            distribute=distribute_util.broadcast(),
        )
        gamma = flow.get_variable(
            name="gamma",
            shape=params_shape,
            dtype=params_dtype,
            initializer=flow.ones_initializer(),
            trainable=trainable,
            distribute=distribute_util.broadcast(),
        )
        moving_mean = flow.get_variable(
            name="moving_mean",
            shape=params_shape,
            dtype=params_dtype,
            initializer=flow.zeros_initializer(),
            trainable=False,
            distribute=distribute_util.broadcast(),
        )
        moving_variance = flow.get_variable(
            name="moving_variance",
            shape=params_shape,
            dtype=params_dtype,
            initializer=flow.ones_initializer(),
            trainable=False,
            distribute=distribute_util.broadcast(),
        )
    builder = (
        flow.user_op_builder(name)
        .Op("normalization")
        .Input("x", [inputs])
        .Input("moving_mean", [moving_mean])
        .Input("moving_variance", [moving_variance])
        .Input("gamma", [gamma])
        .Input("beta", [beta])
        .Output("y")
        .Attr("axis", 1)
        .Attr("epsilon", 1.001e-5)
        .Attr("training", training)
        .Attr("momentum", 0.997)
    )
    if trainable and training:
        builder = builder.Output("mean").Output("inv_variance")
    return builder.Build().InferAndTryRun().RemoteBlobList()[0]

def batch_norm(input, name, axis=1, reuse=False, trainable=True):
    # use separated BN from real and fake batch
    name = name+'_reuse' if reuse else name
    return _batch_norm(input, name, trainable=trainable)

def max_pool2d(input, size, strides, name, padding="VALID", data_format="NCHW", reuse=False):
    name = name+'_reuse' if reuse else name
    return flow.nn.max_pool2d(input, ksize=size, strides=strides, padding=padding, data_format=data_format, name=name)

init = flow.random_normal_initializer(stddev=0.02)

def conv1x1(
    input,
    filters=64,
    name="conv1x1",
    strides=1,
    trainable=True,
    reuse=False,
    use_bias=True,
):
    name_ = name if reuse == False else name + "_reuse"

    # (output_dim, k_h, k_w, input.shape[3]) if NHWC
    weight_shape = (filters, input.shape[1], 1, 1)
    weight = flow.get_variable(
        name + "-weight",
        shape=weight_shape,
        dtype=input.dtype,
        initializer=init,
        trainable=trainable,
        reuse=reuse,
    )

    output = flow.nn.conv2d(
        input,
        weight,
        strides=strides,
        padding="valid",
        data_format="NCHW",
        name=name_,
    )

    if use_bias:
        bias = flow.get_variable(
            name + "-bias",
            shape=(filters,),
            dtype=input.dtype,
            initializer=flow.constant_initializer(0.0),
            trainable=trainable,
            reuse=reuse,
        )

        output = flow.nn.bias_add(output, bias, "NCHW")
    return output

def conv3x3(
    input,
    filters=64,
    name="conv3x3",
    strides=1,
    trainable=True,
    reuse=False,
    use_bias=True,
):
    name_ = name if reuse == False else name + "_reuse"

    # (output_dim, k_h, k_w, input.shape[3]) if NHWC
    weight_shape = (filters, input.shape[1], 3, 3)
    weight = flow.get_variable(
        name + "-weight",
        shape=weight_shape,
        dtype=input.dtype,
        initializer=init,
        trainable=trainable,
        reuse=reuse,
    )

    output = flow.nn.conv2d(
        input,
        weight,
        strides=strides,
        padding="same",
        data_format="NCHW",
        name=name_,
    )

    if use_bias:
        bias = flow.get_variable(
            name + "-bias",
            shape=(filters,),
            dtype=input.dtype,
            initializer=flow.constant_initializer(0.0),
            trainable=trainable,
            reuse=reuse,
        )

        output = flow.nn.bias_add(output, bias, "NCHW")
    return output

def residual_block(inputs, name, trainable=True):
    with flow.scope.namespace(name):
        conv1 = conv3x3(inputs, name="conv1", trainable=trainable)
        # prelu1 = flow.layers.prelu(bn1, name='prelu', trainable=trainable)
        relu1 = flow.math.relu(conv1)
        conv2 = conv3x3(relu1, name="conv2", trainable=trainable)

    return inputs + conv2

def residual_blocks(inputs, block_num, name, trainable=True):
    output = inputs
    # outputs = []
    for i in range(block_num):
        block_name = name + "block%d" % (i)
        output = residual_block(output, block_name, trainable=trainable)
        # outputs.append(output)
    return output

def SFE(x, trainable=True):
    x = conv3x3(x, 64, "SFE_0", trainable=trainable)
    x = flow.math.relu(x)
    x1 = x
    x = residual_blocks(x, 16, "rb_", trainable=trainable)
    x = conv3x3(x, 64, "SFE_1", trainable=trainable)
    x = x + x1
    return x

def CSFI2(x1, x2, trainable=True):
    x12 = flow.layers.upsample_2d(x1, (2, 2), interpolation='bilinear', name='upsanple2')
    x12 = conv1x1(x12, 64, "CSFI2_0", trainable=trainable)
    x12 = flow.math.relu(x12)
    x21 = conv3x3(x2, 64, "CSFI2_1", 2, trainable)
    x21 = flow.math.relu(x21)

    x1 = conv3x3(flow.concat((x1, x21), axis=1), 64, "CSFI2_2", trainable=trainable)
    x1 = flow.math.relu(x1)
    x2 = conv3x3(flow.concat((x2, x12), axis=1), 64, "CSFI2_3", trainable=trainable)
    x2 = flow.math.relu(x2)

    return x1, x2

def CSFI3(x1, x2, x3, trainable=True):
    x12 = flow.layers.upsample_2d(x1, (2, 2), interpolation='bilinear', name='upsanple4')
    x12 = conv1x1(x12, 64, "CSFI3_0", trainable=trainable)
    x12 = flow.math.relu(x12)
    x13 = flow.layers.upsample_2d(x1, (4, 4), interpolation='bilinear', name='upsanple5')
    x13 = conv1x1(x13, 64, "CSFI3_1", trainable=trainable)
    x13 = flow.math.relu(x13)

    x21 = conv3x3(x2, 64, "CSFI3_2", 2, trainable)
    x13 = flow.math.relu(x13)
    x23 = flow.layers.upsample_2d(x2, (2, 2), interpolation='bilinear', name='upsanple6')
    x23 = conv1x1(x23, 64, "CSFI3_3", trainable=trainable)
    x23 = flow.math.relu(x23)

    x31 = conv3x3(x3, 64, "CSFI3_4", 2, trainable)
    x31 = flow.math.relu(x31)
    x31 = conv3x3(x31, 64, "CSFI3_5", 2, trainable)
    x31 = flow.math.relu(x31)
    x32 = conv3x3(x3, 64, "CSFI3_6", 2, trainable)
    x32 = flow.math.relu(x32)

    x1 = conv3x3(flow.concat((x1, x21, x31), axis=1), 64, "CSFI3_7", trainable=trainable)
    x1 = flow.math.relu(x1)
    x2 = conv3x3(flow.concat((x2, x12, x32), axis=1), 64, "CSFI3_8", trainable=trainable)
    x2 = flow.math.relu(x2)
    x3 = conv3x3(flow.concat((x3, x13, x23), axis=1), 64, "CSFI3_9", trainable=trainable)
    x3 = flow.math.relu(x3)

    return x1, x2, x3

def MergeTail(x1, x2, x3, trainable=True):
    x13 = flow.layers.upsample_2d(x1, (4, 4), interpolation='bilinear', name='upsanple7')
    x13 = conv1x1(x13, 64, "MergeTail_0", trainable=trainable)
    x13 = flow.math.relu(x13)
    x23 = flow.layers.upsample_2d(x2, (2, 2), interpolation='bilinear', name='upsanple8')
    x23 = conv1x1(x23, 64, "MergeTail_1", trainable=trainable)
    x23 = flow.math.relu(x23)

    x = conv3x3(flow.concat((x3, x13, x23), axis=1), 64, "MergeTail_2", trainable=trainable)
    x = flow.math.relu(x)
    x = conv3x3(x, 32, "MergeTail_3", trainable=trainable)
    x = conv1x1(x, 3, "MergeTail_4", trainable=trainable)
    x = flow.clamp(x, -1, 1)

    return x

def PixelShuffle(input, r):
    b, c, h, w = input.shape
    assert c % (r * r) == 0
    new_c = int(c / (r * r))
    out = flow.reshape(input, [b, new_c, r * r, h, w])
    out = flow.reshape(out, [b * new_c, r, r, h, w])
    out = flow.transpose(out, [0, 3, 1, 4, 2])
    out = flow.reshape(out, [b, new_c, h * r, w * r])
    return out


from django.urls import path
from . import views

urlpatterns = [
    path('v1/',views.view1),
    path('add/',views.add),
    path('hm/',views.home,name='home' ),
    path('ab/',views.about,name='about'),
    path('co/',views.contact,name='contact'),
    path('as/',views.allStudent),
    path('em/',views.allEmployee),

]


import pyodbc

class PhoneBook:

    def __init__(self, dbname, tname):
        self.dbname = dbname
        self.tname = tname
        self.connString = 'Driver={SQL Server};Server=DESKTOP-DH4N9T0\SQLEXPRESS01;Database='+dbname+';Trusted_Connection=yes;'
        conn = pyodbc.connect(self.connString)
        cursor = conn.cursor()
        cursor.execute(f"SELECT * FROM {tname}")
        self.pb = dict()
        for contact in cursor:
            self.pb.update({contact[0]:contact[1]})
        conn.close()

    def listContacts(self):
        print("Name\t\tPhone")
        for i in sorted(self.pb.keys()):
            print("{}\t\t{}".format(i, self.pb[i]))

    def addContact(self, name, phno):
        if name not in self.pb.keys():
            self.pb.update({name:phno})
            print("1 entry added")
        else:
            print("entry exists")

    def searchByName(self, name):
        if name in self.pb.keys():
            print("entry found - ", name, "-", self.pb[name])
        else:
            print("entry not found")

    def searchByNumber(self, phno):
        if phno in self.pb.values():
            for k,v in self.pb.items():
                if phno == v:
                    name = k
                    break
            print("entry found - ", name, "-", phno)
        else:
            print("entry not found")

    def deleteContact(self, name):
        if name in self.pb.keys():
            del self.pb[name]
            print("1 entry ({}) deleted".format(name))
        else:
            print("entry does not exist")

    def commit(self):
        conn = pyodbc.connect(self.connString)
        cursor = conn.cursor()
        cursor.execute(f"TRUNCATE TABLE {self.tname}")
        for k,v in self.pb.items():
            cursor.execute("INSERT INTO {} (name, phno) VALUES ('{}', '{}')".format(self.tname, k,v))
        print("Committed edits")
        conn.commit()
        conn.close()

# book1 = PhoneBook("inapp", "phonebook")
# book1.listContacts()
# book1.addContact("Kripa", "784512")
# book1.searchByName("Kripa")
# book1.searchByNumber("465132")
# book1.deleteContact("Karikku")
# book1.commit()
# del book1
# book1 = PhoneBook("inapp", "phonebook")
# book1.listContacts()


import heapq
class MedianFinder(object):

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.maxheap=[]
        self.minheap=[]

    '''
    Thinking about the balancing part case by case
    There will be only 2 cases for the initial conditions
    '''

    def addNum(self, num):
        """
        :type num: int
        :rtype: void
        """

        #Step1:push the ele into the maxheap
        heapq.heappush(self.maxheap,-1.0*num)

        #Step2:matain balancing
        heapq.heappush(self.minheap,-1.0*heapq.heappop(self.maxheap))

        #Step3:check if you need to reba;ance
        if len(self.maxheap)<len(self.minheap):
            heapq.heappush(self.maxheap,-1.0*heapq.heappop(self.minheap))

    def findMedian(self):
        """
        :rtype: float
        """
        maxhead=minhead=0.0
        if len(self.maxheap)!=0:
            maxhead=heapq.heappop(self.maxheap)
            heapq.heappush(self.maxheap,maxhead)
        if len(self.minheap)!=0:
            minhead=heapq.heappop(self.minheap)
            heapq.heappush(self.minheap,minhead)
        #even number of eles
        if (len(self.maxheap)+len(self.minheap))%2==0:
            return (-1.0*maxhead+minhead)/2
        else:
            return -1.0*maxhead


import math
import random

def set_seed(seed):
    random.seed(seed)

def dd_algorithm(n, theta, m):
    # Initialize variables
    infectedNo = round(math.pow(n, theta))
    delta = round((m * math.log(2)) / infectedNo)
    if delta == 0:
        return set()
    positiveTests = set()
    markedIndividuals = set()
    positiveTestsWith1Individual = {}
    """
    The bipartite graph generated by the algorithm is independent to the permutation of individuals in the input
     population. For ease of implementation, this implementation considers individuals in range 0 ≤ i < a to be infected
     , and individuals in range a ≤ i < n non-infected (where a is the number of infected individuals, and n is the
     population size).
    """
    for individual in range(n):
        # Find delta unique tests to match to each individual
        matchedTests = random.sample(range(n, n + m), delta)
        # Match the individuals to tests
        if individual < infectedNo:
            # If the individual is in the infected range, then label any connected tests as +ve
            for test in matchedTests:
                if test not in positiveTests:
                    # Only preserve test nodes which are connected to only one individual
                    positiveTestsWith1Individual[test] = individual
                elif test in positiveTestsWith1Individual:
                    positiveTestsWith1Individual.pop(test)
                positiveTests.add(test)
        else:
            """
            If the individual is due to be matched to a negative test then it is not added to the graph, as it
            would've been removed anyway. If the individual is due to be matched with only +ve tests, then
            check which tests in positiveTestsWith1Individual are affected. No new tests are added to this dict,
            as no more +ve tests can be created.
            """
            add = True
            for test in matchedTests:
                if test not in positiveTests:
                    add = False
                    break
            if add:
                for test in matchedTests:
                    if test in positiveTestsWith1Individual:
                        positiveTestsWith1Individual.pop(test)
    # Return the set of values for the positiveTestsWith1Individual dictionary
    for test in positiveTestsWith1Individual:
        markedIndividuals.add(positiveTestsWith1Individual[test])
    return markedIndividuals


import os
import random
import discord

from discord.ext import commands
from dotenv import load_dotenv
from datetime import timedelta, datetime

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
date = None

bot = commands.Bot(command_prefix='-')

# display a message in console to tell admins that the bot is online
@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')

# @bot.event
# async def on_message(message):
#     bot.wait_until_ready()
#     x = random.randint(0, 100)
#     if x == 69:
#         await message.send("https://www.change.org/plzsign_1_")
#     await bot.process_commands(message)

# When ever a new member joins, the bot will send them a dm to welcome them
@bot.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(
        f'Hi {member.name}, welcome to the go server !'
    )

# give meeting time
@bot.command(name='settime', help="Sets the meeting time")
@commands.has_any_role('Officer','Teacher', 483412758621323264)
async def setMeetingTime(ctx, *, message):
    global date
    date = message

#next
@bot.command(name='meeting', help="||Tell you next metting time or something")
async def nine_nine(ctx):
    if ctx.author == bot.user:
        return
    print(date)
    await ctx.reply(date)

#bans a user with a reason
# @bot.command(name='test', help="|| test command don't tuch")
# @commands.has_permissions(ban_members = True)
# async def ban(ctx, member : discord.Member, *, reason = None):
#     await member.ban(reason = reason)

# #give role to a member
@bot.command()
async def giverole(ctx, arg: discord.Member):
    await ctx.send(arg)
    knownrole = discord.utils.get(ctx.guild.roles, name="Mod")
    await arg.add_roles(knownrole)

# #spam
# @bot.command(name='spam')
# async def nine_nine(ctx):
#     for i in range (10):
#         await ctx.send("@everyone")
#         i=i+1

bot.run(TOKEN)


from twisted.python.runtime import platform
from twisted.internet.test.reactormixins import ReactorBuilder
from twisted.internet.protocol import Protocol
if not platform.isWindows():
    from twisted.internet._posixstdio import StandardIO

class StdioFilesTests(ReactorBuilder):
    """
    L{StandardIO} supports reading and writing to filesystem files.
    """

    def setUp(self):
        path = self.mktemp()
        file(path, "w").close()
        self.extraFile = file(path, "r+")

    def test_addReader(self):
        """
        Adding a filesystem file reader to a reactor will make sure it is
        polled.
        """
        reactor = self.buildReactor()

        class DataProtocol(Protocol):
            data = ""
            def dataReceived(self, data):
                self.data += data
                # It'd be better to stop reactor on connectionLost, but that
                # fails on FreeBSD, probably due to
                # http://bugs.python.org/issue9591:
                if self.data == "hello!":
                    reactor.stop()

        path = self.mktemp()
        f = file(path, "w")
        f.write("hello!")
        f.close()
        f = file(path, "r")

        # Read bytes from a file, deliver them to a protocol instance:
        protocol = DataProtocol()
        StandardIO(protocol, stdin=f.fileno(),
                   stdout=self.extraFile.fileno(),
                   reactor=reactor)

        self.runReactor(reactor)
        self.assertEqual(protocol.data, "hello!")

    def test_addWriter(self):
        """
        Adding a filesystem file writer to a reactor will make sure it is
        polled.
        """
        reactor = self.buildReactor()

        class DisconnectProtocol(Protocol):
            def connectionLost(self, reason):
                reactor.stop()

        path = self.mktemp()
        f = file(path, "w")

        # Write bytes to a transport, hopefully have them written to a file:
        protocol = DisconnectProtocol()
        StandardIO(protocol, stdout=f.fileno(),
                   stdin=self.extraFile.fileno(), reactor=reactor)
        protocol.transport.write("hello")
        protocol.transport.write(", world")
        protocol.transport.loseConnection()

        self.runReactor(reactor)
        f.close()
        f = file(path, "r")
        self.assertEqual(f.read(), "hello, world")
        f.close()

    def test_removeReader(self):
        """
        Removing a filesystem file reader from a reactor will make sure it is
        no longer polled.
        """
        reactor = self.buildReactor()
        self.addCleanup(self.unbuildReactor, reactor)

        path = self.mktemp()
        file(path, "w").close()
        # Cleanup might fail if file is GCed too soon:
        self.f = f = file(path, "r")

        # Have the reader added:
        stdio = StandardIO(Protocol(), stdin=f.fileno(),
                           stdout=self.extraFile.fileno(),
                           reactor=reactor)
        self.assertIn(stdio._reader, reactor.getReaders())
        stdio._reader.stopReading()
        self.assertNotIn(stdio._reader, reactor.getReaders())

    def test_removeWriter(self):
        """
        Removing a filesystem file writer from a reactor will make sure it is
        no longer polled.
        """
        reactor = self.buildReactor()
        self.addCleanup(self.unbuildReactor, reactor)

        # Cleanup might fail if file is GCed too soon:
        self.f = f = file(self.mktemp(), "w")

        # Have the reader added:
        protocol = Protocol()
        stdio = StandardIO(protocol, stdout=f.fileno(),
                           stdin=self.extraFile.fileno(),
                           reactor=reactor)
        protocol.transport.write("hello")
        self.assertIn(stdio._writer, reactor.getWriters())
        stdio._writer.stopWriting()
        self.assertNotIn(stdio._writer, reactor.getWriters())

    def test_removeAll(self):
        """
        Calling C{removeAll} on a reactor includes descriptors that are
        filesystem files.
        """
        reactor = self.buildReactor()
        self.addCleanup(self.unbuildReactor, reactor)

        path = self.mktemp()
        file(path, "w").close()
        # Cleanup might fail if file is GCed too soon:
        self.f = f = file(path, "r")

        # Have the reader added:
        stdio = StandardIO(Protocol(), stdin=f.fileno(),
                           stdout=self.extraFile.fileno(), reactor=reactor)
        # And then removed:
        removed = reactor.removeAll()
        self.assertIn(stdio._reader, removed)
        self.assertNotIn(stdio._reader, reactor.getReaders())

    def test_getReaders(self):
        """
        C{reactor.getReaders} includes descriptors that are filesystem files.
        """
        reactor = self.buildReactor()
        self.addCleanup(self.unbuildReactor, reactor)

        path = self.mktemp()
        file(path, "w").close()
        # Cleanup might fail if file is GCed too soon:
        self.f = f = file(path, "r")

        # Have the reader added:
        stdio = StandardIO(Protocol(), stdin=f.fileno(),
                           stdout=self.extraFile.fileno(), reactor=reactor)
        self.assertIn(stdio._reader, reactor.getReaders())

    def test_getWriters(self):
        """
        C{reactor.getWriters} includes descriptors that are filesystem files.
        """
        reactor = self.buildReactor()
        self.addCleanup(self.unbuildReactor, reactor)

        # Cleanup might fail if file is GCed too soon:
        self.f = f = file(self.mktemp(), "w")

        # Have the reader added:
        stdio = StandardIO(Protocol(), stdout=f.fileno(),
                           stdin=self.extraFile.fileno(), reactor=reactor)
        self.assertNotIn(stdio._writer, reactor.getWriters())
        stdio._writer.startWriting()
        self.assertIn(stdio._writer, reactor.getWriters())

    if platform.isWindows():
        skip = ("StandardIO does not accept stdout as an argument to Windows.  "
                "Testing redirection to a file is therefore harder.")

globals().update(StdioFilesTests.makeTestCaseClasses())


import argparse
import os

import cv2 as cv
import numpy as np
import pytesseract as ocr
from pytesseract.pytesseract import run_tesseract

WHITE = 0
BLACK = 1

def load_image(path):
    """
    loads the pixel matrix that represents the image stored in `path`
    :param path: the file path to the image
    :return: the np array representing that image
    """
    return cv.imread(path, 0)

def normalize_img(img, min, max):
    norm_img = np.zeros(np.shape(img))
    norm_img = cv.normalize(img, norm_img, min, max, cv.NORM_MINMAX)
    return norm_img

def save_img(img, name):
    cv.imwrite(name, img)

def is_line(black_pixel_rate, white_to_black_transition_rate):
    return .1 < black_pixel_rate < .5 and white_to_black_transition_rate > .2

def is_word(black_pixel_rate, white_to_black_transition_rate):
    return .1 < black_pixel_rate < .6 and white_to_black_transition_rate > .2

def is_char(black_pixel_rate, white_to_black_transition_rate):
    return .1 < black_pixel_rate < .8 and white_to_black_transition_rate < .7

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument("name", metavar="IMAGE_NAME",
                        help="image file name without extension")
    parser.add_argument("--p", default="./imgs",
                        help="input image file path")
    parser.add_argument("--op", default="./imgs/out",
                        help="output image path")
    parser.add_argument("--out",
                        help="output image file prefix")
    parser.add_argument("--ocr", action="store_true",
                        help="use tesseract to try to parse identified text segments")
    parser.add_argument("--lang", default="eng",
                        help="text language. Only makes sense when using --ocr")
    parser.add_argument("--seg", choices=["char", "word", "line"], default="line",
                        help="search for `line`s, `char`s or `word`s")

    try:
        args = parser.parse_args()
    except:
        parser.print_help()
        exit(-1)

    seg = args.seg
    output_path = args.op

    if not os.path.exists(output_path):
        os.makedirs(output_path)
    if not os.path.exists("{}/{}".format(output_path, seg)):
        os.makedirs("{}/{}".format(output_path, seg))
    if not os.path.exists("{}/comp".format(output_path)):
        os.makedirs("{}/comp".format(output_path))
    if not os.path.exists("{}/comp/{}".format(output_path, seg)):
        os.makedirs("{}/comp/{}".format(output_path, seg))
    if not os.path.exists("{}/{}/tess".format(output_path, seg)):
        os.makedirs("{}/{}/tess".format(output_path, seg))
        os.makedirs("{}/{}/tess/text".format(output_path, seg))

    img_name = args.name
    img_path = args.p
    if not args.out:
        args.out = img_name
    img_out_name = args.out

    img = load_image("{}/{}.pbm".format(img_path, img_name))
    img = normalize_img(img, WHITE, BLACK).astype(int)
    black_pixels = np.where(img == BLACK)
    white_pixels = np.where(img == WHITE)
    img[black_pixels] = WHITE
    img[white_pixels] = BLACK

    img = np.array(img, dtype=np.uint8)
    text_img = np.copy(img)

    kernel_1 = {
        "char": np.array(np.ones((9, 1)) * BLACK, dtype=np.uint8),
        "word": np.array(np.ones((7, 12)) * BLACK, dtype=np.uint8),
        "line": np.array(np.ones((1, 100)) * BLACK, dtype=np.uint8)
    }[seg]

    img1 = cv.morphologyEx(img, cv.MORPH_DILATE, kernel_1)
    save_img(img1, "{}/{}/{}_step_1.pbm".format(output_path, seg, img_out_name))

    img2 = cv.morphologyEx(img1, cv.MORPH_ERODE, kernel_1)
    save_img(img2, "{}/{}/{}_step_2.pbm".format(output_path, seg, img_out_name))

    kernel_3 = {
        "char": np.array(np.ones((5, 1)) * BLACK, dtype=np.uint8),
        "word": np.array(np.ones((50, 1)) * BLACK, dtype=np.uint8),
        "line": np.array(np.ones((200, 1)) * BLACK, dtype=np.uint8)
    }[seg]

    img3 = cv.morphologyEx(img, cv.MORPH_DILATE, kernel_3)
    save_img(img3, "{}/{}/{}_step_3.pbm".format(output_path, seg, img_out_name))

    img4 = cv.morphologyEx(img3, cv.MORPH_ERODE, kernel_3)
    save_img(img4, "{}/{}/{}_step_4.pbm".format(output_path, seg, img_out_name))

    img5 = cv.bitwise_and(img2, img4)
    save_img(img5, "{}/{}/{}_step_5.pbm".format(output_path, seg, img_out_name))

    kernel_6 = {
        "char": np.array(np.ones((1, 1)) * BLACK, dtype=np.uint8),
        "word": np.array(np.ones((5, 10)) * BLACK, dtype=np.uint8),
        "line": np.array(np.ones((1, 30)) * BLACK, dtype=np.uint8)
    }[seg]
    img6 = cv.morphologyEx(img5, cv.MORPH_CLOSE, kernel_6)
    save_img(img6, "{}/{}/{}_step_6.pbm".format(output_path, seg, img_out_name))

    img7 = np.copy(img6)
    num_comp, img7 = cv.connectedComponents(img6, img7, 8)
    print("Found {} connected components".format(num_comp))

    img7b = load_image("{}/{}/{}_step_6.pbm".format(output_path, seg, img_out_name))
    img7c = np.copy(img7b)
    contours, hierarchy = cv.findContours(img7b, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    idx = 0
    text_cont = 0
    is_text = {
        "char": is_char,
        "word": is_word,
        "line": is_line
    }[seg]
    tesseract_config = {
        "char": "--psm 10",
        "word": "--psm 8",
        "line": "--psm 13"
    }[seg]
    for cnt in contours:
        idx += 1
        x, y, w, h = cv.boundingRect(cnt)

        roi = text_img[y:y + h, x:x + w]
        save_img(roi, "{}/comp/{}/{}_step_7_{}.pbm".format(output_path, seg, img_out_name, idx))
        roi_black_pixels = np.count_nonzero(roi == BLACK)
        # print("Black Pixels for idx {}: {}".format(idx, roi_black_pixels))
        black_pixels_rate = roi_black_pixels / (w * h)
        print("Black Pixels Rate for idx {}: {}".format(idx, black_pixels_rate))
        roi_v = np.count_nonzero(roi[:-1, :] - roi[1:, :] == BLACK)
        roi_h = np.count_nonzero(roi[:, :-1] - roi[:, 1:] == BLACK)
        # print("Vertical white to black transition for idx {}: {}".format(idx, roi_v))
        # print("Horizontal white to black transition for idx {}: {}".format(idx, roi_h))
        transition_rate = (roi_v + roi_h) / roi_black_pixels if roi_black_pixels != 0 else 0.
        print("Black Pixels Transition Rate for idx {}: {}".format(idx, transition_rate))

        # draw rectangle to visualize the bounding rect
        cv.rectangle(img7c, (x, y), (x + w, y + h), color=1, thickness=1)
        if is_text(black_pixels_rate, transition_rate):
            if args.ocr:
                cv.putText(text_img, str(idx),
                           (x, y), color=1, fontFace=cv.FONT_HERSHEY_PLAIN, fontScale=1)
                padding_y, padding_x = y - 5 if y > 5 else y, x - 5 if x > 5 else x
                save_img(normalize_img(img[padding_y:y + h, padding_x:x + w], 0, 255), "{}/{}/tess/{}__{}.png".format(output_path, seg, img_out_name, idx))
                run_tesseract(input_filename="{}/{}/tess/{}__{}.png".format(output_path, seg, img_out_name, idx),
                              output_filename_base="{}/{}/tess/text/{}__{}".format(output_path, seg, img_out_name, idx),
                              extension="png",
                              lang=args.lang,
                              config=tesseract_config,
                              nice=0)
            text_cont += 1
            cv.rectangle(text_img, (x, y), (x + w, y + h), color=1, thickness=1)
    save_img(img7c, "{}/{}/{}_step_7.pbm".format(output_path, seg, img_out_name))
    print("Found {} text parts".format(text_cont))

    black_pixels = np.where(text_img == BLACK)
    white_pixels = np.where(text_img == WHITE)
    text_img[black_pixels] = WHITE
    text_img[white_pixels] = BLACK
    save_img(text_img, "{}/{}/{}_text.pbm".format(output_path, seg, img_out_name))


#!/usr/bin/env python2

from rest_framework import serializers

from domain.achievement.models.Action import Action
from custom_fields.ChoicesField import ChoicesField

class ActionSerializer(serializers.ModelSerializer):
    action_verb = ChoicesField(choices=Action.ACTION_VERBS)

    class Meta:
        model = Action
        fields = (
            'id',
            'goal',
            'action_verb',
            'activity',
            'target_metric',
            'target_metric_unit',
            'created_date',
            'updated_date',
        )


import mysql.connector
import pandas as pd
import streamlit as st
import random

def add_new_user(conn:mysql.connector.connect, username, password, name, email):
    cur = conn.cursor()
    query = f"""
        INSERT INTO users
        values ('{username}', '{password}', '{email}');
        """
    cur.execute(query)
    conn.commit()

def view_cart_items(conn:mysql.connector.connect, username):
    cur = conn.cursor()
    query = f"""
    SELECT * FROM buy where username='{username}';
    """
    cur.execute(query)
    data = cur.fetchall()
    buy_df = pd.DataFrame(data, columns=['buy_id', 'username', 'product_id'])
    return buy_df

def delete_item_from_cart(conn:mysql.connector.connect, buy_id):
    cur = conn.cursor()
    query = f"""
    DELETE FROM buy
    WHERE buy_id='{buy_id}';
    """
    cur.execute(query)
    conn.commit()

def is_no_duplicate(conn:mysql.connector.connect, username, product_id):
    cur = conn.cursor()
    query = f"""
    SELECT * FROM buy where username='{username}';
    """
    cur.execute(query)
    data = cur.fetchall()
    buy_df = pd.DataFrame(data, columns=['buy_id', 'username', 'product_id'])
    all_product_ids = list(buy_df.get('product_id'))
    if not product_id in all_product_ids:
        return True

    return False

def add_to_cart(conn:mysql.connector.connect, username, product_id):
    if is_no_duplicate(conn, username, product_id):
        cur = conn.cursor()
        query = """
        SELECT * FROM buy;
        """
        cur.execute(query)
        data = cur.fetchall()
        buy_df = pd.DataFrame(data, columns=['buy_id', 'username', 'product_id'])
        all_ids = list(buy_df.get('buy_id'))

        num = random.randint(0, 10000)
        while num in all_ids:
            num = random.randint(0, 10000)

        query = f"""
        INSERT INTO buy
        values ('{num}', '{username}', '{product_id}');
        """

        cur.execute(query)
        conn.commit()

def fetch_all_products(conn:mysql.connector.connect):
    cur = conn.cursor()

    query = """
    SELECT * FROM products;
    """
    cur.execute(query)
    data = cur.fetchall()
    product_df = pd.DataFrame(data, columns=['product_id', 'product_name', 'price', 'seller', 'description'])
    return product_df

def get_product(conn:mysql.connector.connect, product_id):
    cur = conn.cursor()

    query = f"""
    SELECT * FROM products WHERE product_id='{product_id}';
    """
    cur.execute(query)
    data = cur.fetchall()
    product_df = pd.DataFrame(data, columns=['product_id', 'product_name', 'price', 'seller', 'description'])
    return product_df

# Connect to database and return the database connection object.
def connect():

    try:
        # Connect to server
        # MySQL database configuration setup in .streamlit/secrets.toml file.
        connect_db = mysql.connector.connect(**st.secrets["mysql"])
        print("Connect success!")

    except Exception as ex:
        print(ex)

    return connect_db

# test session
if __name__ == '__main__':
    pass


# Nhập độ dài
b=float(input('nhập b là độ dài cạnh b:'))
a=float(input('Nhập a là độ dài cạnh a:'))

#Thêm điều kiện cơ bản đẻ chạy chương trình:
if a<0 or b<0 or a==0 or b==0:
    print('xin mời chạy và nhập đúng dữ liệu')
else:
    c=(a+b)*2
    s=a*b
    print('Chu vi:',c)
    print('Diện tích:',s)


try:
    from commands.creation.creation_commands import CreationCommand
    from dna.dna import Dna
    from dna.dna_sequence import DnaSequence
except ImportError:
    print("Need to fix the installation")
    raise
'''
New Command.
command: new <seq> [@<seq_name>]
if name is not provided a default name is set to be: seq.
'''

class NewCommand(CreationCommand):
    __id = 1

    def __init__(self, args):
        name, dna_sequence = self.parse(args)
        self.__name = self.validate_name(name, 'seq')
        self.__dna_sequence = DnaSequence(dna_sequence)
        self.__dna = Dna(dna_sequence, self.__name)

    def execute(self):
        self.print(Dna.get_id(), self.__dna.get_name(), self.__dna_sequence)
        self.__dna.execute()

    @staticmethod
    def get_id():
        return NewCommand.__id

    @staticmethod
    def set_id(id):
        NewCommand.__id += id


def earliestBus(timestamp, buses):
  waitTime = 0
  while True:
    for bus in buses:
      if (timestamp + waitTime) % bus == 0:
        return { 'id' : bus, 'wait_time': waitTime }
    waitTime += 1

def main():
  f = open("./inputs.txt")
  timestamp = int(f.readline())
  buses =  f.readline()[:-1].split(',')
  while 'x' in buses:
    buses.remove('x')
  buses = list(map(lambda x: int(x), buses))
  res = earliestBus(timestamp, buses)
  print(res['wait_time'] * res['id'])

if __name__ == "__main__":
  main()


#!/usr/bin/env python
# coding: utf-8
# Original github: https://github.com/peteryuX/retinaface-tf2 ##############
# In[3]:

import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.applications import MobileNetV2, ResNet50
from tensorflow.keras.layers import Input, Conv2D, ReLU, LeakyReLU
import sys
import numpy as np
import cv2

from anchor import decode_tf, prior_box_tf, prior_box

# In[4]:

def _regularizer(weights_decay):
    """l2 regularizer"""
    return tf.keras.regularizers.l2(weights_decay)

def _kernel_init(scale=1.0, seed=None):
    """He normal initializer"""
    return tf.keras.initializers.he_normal()

# In[5]:

class BatchNormalization(tf.keras.layers.BatchNormalization):
    """Make trainable=False freeze BN for real (the og version is sad).
       ref: https://github.com/zzh8829/yolov3-tf2
    """
    def __init__(self, axis=-1, momentum=0.9, epsilon=1e-5, center=True,
                 scale=True, name=None, **kwargs):
        super(BatchNormalization, self).__init__(
            axis=axis, momentum=momentum, epsilon=epsilon, center=center,
            scale=scale, name=name, **kwargs)

    def call(self, x, training=False):
        if training is None:
            training = tf.constant(False)
        training = tf.logical_and(training, self.trainable)

        return super().call(x, training)

# In[6]:

def Backbone(backbone_type='MobileNetV2', use_pretrain=True):
    """Backbone Model"""
    weights = None
    if use_pretrain:
        weights = 'imagenet'

    def backbone(x):
        if backbone_type == 'MobileNetV2':
            extractor = MobileNetV2(input_shape=x.shape[1:], include_top=False, weights=weights)
            pick_layer1 = 54  # C3 layer, which is [80, 80, 32] in original retinaface model
            pick_layer2 = 116                    # [40, 40, 96]
            pick_layer3 = 143                    # [20, 20, 160]
            preprocess = tf.keras.applications.mobilenet_v2.preprocess_input
        elif backbone_type == 'ResNet50':
            extractor = ResNet50(input_shape=x.shape[1:], include_top=False, weights=weights)
            pick_layer1 = 80  # [80, 80, 512]
            pick_layer2 = 142  # [40, 40, 1024]
            pick_layer3 = 174  # [20, 20, 2048]
            preprocess = tf.keras.applications.resnet.preprocess_input
        else:
            raise NotImplementedError(
                'Backbone type {} is not recognized.'.format(backbone_type))

        return Model(extractor.input,
                     (extractor.layers[pick_layer1].output,
                      extractor.layers[pick_layer2].output,
                      extractor.layers[pick_layer3].output),
                     name=backbone_type + '_extrator')(preprocess(x))

    return backbone

"""this is a a nested function or closure."""

# In[ ]:

# In[7]:

class ConvUnit(tf.keras.layers.Layer):
    """Conv + BN + Act"""
    def __init__(self, f, k, s, wd, act=None, name='ConvBN', **kwargs):
        super(ConvUnit, self).__init__(name=name, **kwargs)
        self.conv = Conv2D(filters=f, kernel_size=k, strides=s, padding='same',
                           kernel_initializer=_kernel_init(),
                           kernel_regularizer=_regularizer(wd),
                           use_bias=False, name='conv')
        self.bn = BatchNormalization(name='bn')

        if act is None:
            self.act_fn = tf.identity
        elif act == 'relu':
            self.act_fn = ReLU()
        elif act == 'lrelu':
            self.act_fn = LeakyReLU(0.1)
        else:
            raise NotImplementedError(
                'Activation function type {} is not recognized.'.format(act))

    def call(self, x):
        return self.act_fn(self.bn(self.conv(x)))

# In[8]:

class FPN(tf.keras.layers.Layer):
    """Feature Pyramid Network"""
    def __init__(self, out_ch, wd, name='FPN', **kwargs):
        super(FPN, self).__init__(name=name, **kwargs)
        act = 'relu'
        if (out_ch <= 64):
            act = 'lrelu'

        self.output1 = ConvUnit(f=out_ch, k=1, s=1, wd=wd, act=act)
        self.output2 = ConvUnit(f=out_ch, k=1, s=1, wd=wd, act=act)
        self.output3 = ConvUnit(f=out_ch, k=1, s=1, wd=wd, act=act)
        self.merge1 = ConvUnit(f=out_ch, k=3, s=1, wd=wd, act=act)
        self.merge2 = ConvUnit(f=out_ch, k=3, s=1, wd=wd, act=act)

    def call(self, x):
        output1 = self.output1(x[0])  # [80, 80, out_ch]
        output2 = self.output2(x[1])  # [40, 40, out_ch]
        output3 = self.output3(x[2])  # [20, 20, out_ch]

        # Upsampling and Add operation for feature fusion, and then a Conv2D(3*3)
        up_h, up_w = tf.shape(output2)[1], tf.shape(output2)[2]
        up3 = tf.image.resize(output3, [up_h, up_w], method='nearest')
        output2 = output2 + up3
        output2 = self.merge2(output2)

        up_h, up_w = tf.shape(output1)[1], tf.shape(output1)[2]
        up2 = tf.image.resize(output2, [up_h, up_w], method='nearest')
        output1 = output1 + up2
        output1 = self.merge1(output1)

        return output1, output2, output3

"""1. use a 1*1 convolution layer to adjust the number of channel
   2. upsampling
   3. addition"""

# In[9]:

class SSH(tf.keras.layers.Layer):
    """Single Stage Headless Layer"""
    def __init__(self, out_ch, wd, name='SSH', **kwargs):
        super(SSH, self).__init__(name=name, **kwargs)
        assert out_ch % 4 == 0
        act = 'relu'
        if (out_ch <= 64):
            act = 'lrelu'

        self.conv_3x3 = ConvUnit(f=out_ch // 2, k=3, s=1, wd=wd, act=None) #chanel = 32

        self.conv_5x5_1 = ConvUnit(f=out_ch // 4, k=3, s=1, wd=wd, act=act) #chanel = 16
        self.conv_5x5_2 = ConvUnit(f=out_ch // 4, k=3, s=1, wd=wd, act=None)

        self.conv_7x7_2 = ConvUnit(f=out_ch // 4, k=3, s=1, wd=wd, act=act) #chanel = 16
        self.conv_7x7_3 = ConvUnit(f=out_ch // 4, k=3, s=1, wd=wd, act=None)

        self.relu = ReLU()

    def call(self, x):
        conv_3x3 = self.conv_3x3(x)

        conv_5x5_1 = self.conv_5x5_1(x)
        conv_5x5 = self.conv_5x5_2(conv_5x5_1)

        conv_7x7_2 = self.conv_7x7_2(conv_5x5_1)
        conv_7x7 = self.conv_7x7_3(conv_7x7_2)

        output = tf.concat([conv_3x3, conv_5x5, conv_7x7], axis=3) #chanel = 32+16+16=64
        output = self.relu(output)

        return output

"""The purpose of SSH is to use multiple (two in this network) 3*3 convolution
   layers to increase receptive field. This kind of methods can decrease the number of parameters"""

# In[10]:

class BboxHead(tf.keras.layers.Layer):
    """Bbox Head Layer"""
    def __init__(self, num_anchor, wd, name='BboxHead', **kwargs):
        super(BboxHead, self).__init__(name=name, **kwargs)
        self.num_anchor = num_anchor
        self.conv = Conv2D(filters=num_anchor * 4, kernel_size=1, strides=1)

    def call(self, x):
        h, w = tf.shape(x)[1], tf.shape(x)[2]
        x = self.conv(x)

        return tf.reshape(x, [-1, h * w * self.num_anchor, 4])

# In[11]:

class LandmarkHead(tf.keras.layers.Layer):
    """Landmark Head Layer"""
    def __init__(self, num_anchor, wd, name='LandmarkHead', **kwargs):
        super(LandmarkHead, self).__init__(name=name, **kwargs)
        self.num_anchor = num_anchor
        self.conv = Conv2D(filters=num_anchor * 4, kernel_size=1, strides=1)  # There are two keypoints in each anchor, each keypoints have two coordinate values

    def call(self, x):
        h, w = tf.shape(x)[1], tf.shape(x)[2]
        x = self.conv(x)

        return tf.reshape(x, [-1, h * w * self.num_anchor, 4])

# In[12]:

class ClassHead(tf.keras.layers.Layer):
    """Class Head Layer"""
    def __init__(self, num_anchor, wd, name='ClassHead', **kwargs):
        super(ClassHead, self).__init__(name=name, **kwargs)
        self.num_anchor = num_anchor
        self.conv = Conv2D(filters=num_anchor * 2, kernel_size=1, strides=1)

    def call(self, x):
        h, w = tf.shape(x)[1], tf.shape(x)[2]
        x = self.conv(x)

        return tf.reshape(x, [-1, h * w * self.num_anchor, 2])

# In[13]:

def RetinaFaceModel(cfg, training=False, iou_th=0.4, score_th=0.02,
                    name='RetinaFaceModel'):
    """Retina Face Model"""
    input_width = cfg['input_width'] if training else None
    input_height = cfg['input_height'] if training else None
    wd = cfg['weights_decay']
    out_ch = cfg['out_channel']
    num_anchor = len(cfg['min_sizes'][0]) # min_size: size of anchors in each scale. there are three scales and two anchors in each scale.
    backbone_type = cfg['backbone_type']

    # define model
    x = inputs = Input([input_height, input_width, 3], name='input_image')

    x = Backbone(backbone_type=backbone_type)(x)

    fpn = FPN(out_ch=out_ch, wd=wd)(x)

    features = [SSH(out_ch=out_ch, wd=wd, name=f'SSH_{i}')(f)
                for i, f in enumerate(fpn)]

    bbox_regressions = tf.concat(
        [BboxHead(num_anchor, wd=wd, name=f'BboxHead_{i}')(f)
         for i, f in enumerate(features)], axis=1)
    landm_regressions = tf.concat(
        [LandmarkHead(num_anchor, wd=wd, name=f'LandmarkHead_{i}')(f)
         for i, f in enumerate(features)], axis=1)
    classifications = tf.concat(
        [ClassHead(num_anchor, wd=wd, name=f'ClassHead_{i}')(f)
         for i, f in enumerate(features)], axis=1)

    """Each lateral path has its own classification, bounding box, and landmark head;
    therefore, each lateral path creates 3 different outputs.
    However, the processes after multi-task heads are common to each path.
    Therefore, these outcomes are concatenated.

    axis=1 means concatenation along the second dimension (columns)
    """

    classifications = tf.keras.layers.Softmax(axis=-1)(classifications)

    if training:
        out = (bbox_regressions, landm_regressions, classifications)
    else:
        # only for batch size 1
        preds = tf.concat(  # [bboxes, landms, landms_valid, conf]
            [bbox_regressions[0], landm_regressions[0],
             tf.ones_like(classifications[0, :, 0][..., tf.newaxis]),
             classifications[0, :, 1][..., tf.newaxis]], 1)
        priors = prior_box_tf((tf.shape(inputs)[1], tf.shape(inputs)[2]),
                              min_sizes,  steps, clip)
        decode_preds = decode_tf(preds, priors, variances)

        selected_indices = tf.image.non_max_suppression(
            boxes=decode_preds[:, :4],
            scores=decode_preds[:, -1],
            max_output_size=tf.shape(decode_preds)[0],
            iou_threshold=iou_th,
            score_threshold=score_th)

        out = tf.gather(decode_preds, selected_indices)

    return Model(inputs, out, name=name)