# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.11.3
#   kernelspec:
#     display_name: Python 3
#     name: python3
# ---

# + [markdown] id="view-in-github" colab_type="text"
#

# + [markdown] id="Gmm_TyNcTdLD"
# # Adversarial autoencoders for text
#
# Code is from
# https://github.com/shentianxiao/text-autoencoders
#
# Paper is here: https://arxiv.org/pdf/1905.12777.pdf

# + [markdown] id="dV3lykF6TvwL"
# # Setup

# + colab={"base_uri": "https://localhost:8080/"} id="G29OhPQcTdoO" outputId="1bfdb063-5b30-4e65-f1a8-1a7a11e00e9a"
import torch
from multiprocessing import cpu_count
print(cpu_count())
print(torch.cuda.is_available())

# + colab={"base_uri": "https://localhost:8080/"} id="5JtFQPuqTaw2" outputId="cba5e1dc-40be-4a5f-cb9b-777765800836"
# !git clone https://github.com/shentianxiao/text-autoencoders.git

# + colab={"base_uri": "https://localhost:8080/"} id="rSKVhddyUUm2" outputId="423007d3-743f-4dc3-e3e7-ec5af238261a"
# !ls

# + colab={"base_uri": "https://localhost:8080/"} id="qh7fYGg9UWcz" outputId="c2b179ad-ecd6-43a5-85e4-03720518dc08"
# %cd text-autoencoders

# + colab={"base_uri": "https://localhost:8080/"} id="dTmgH_QUUYId" outputId="f1fb7a20-2a84-4f50-af88-58ff3eaff4c4"
# !ls

# + id="jrmT7wGeB6zm"

# + [markdown] id="u-FxMmZ3Txlk"
# # Data

# + colab={"base_uri": "https://localhost:8080/"} id="PJqGHr-KTo9W" outputId="7f168732-337f-4fec-c41c-5a013abe1828"
# !bash download_data.sh

# + [markdown] id="RBD4mGZ_Uqjr"
# # Train

# + colab={"base_uri": "https://localhost:8080/"} id="aPw6uP1MU0qh" outputId="908c9949-75f1-4498-de65-1bc0c823e860"
# !python train.py -h

# + colab={"base_uri": "https://localhost:8080/", "height": 154} id="6rTRlHtdXwwX" outputId="59cc4db5-b540-4d04-a644-a61fa274f213"
'''
# Path arguments
parser.add_argument('--train', metavar='FILE', required=True,
                    help='path to training file')
parser.add_argument('--valid', metavar='FILE', required=True,
                    help='path to validation file')
parser.add_argument('--save-dir', default='checkpoints', metavar='DIR',
                    help='directory to save checkpoints and outputs')
parser.add_argument('--load-model', default='', metavar='FILE',
                    help='path to load checkpoint if specified')
# Architecture arguments
parser.add_argument('--vocab-size', type=int, default=10000, metavar='N',
                    help='keep N most frequent words in vocabulary')
parser.add_argument('--dim_z', type=int, default=128, metavar='D',
                    help='dimension of latent variable z')
parser.add_argument('--dim_emb', type=int, default=512, metavar='D',
                    help='dimension of word embedding')
parser.add_argument('--dim_h', type=int, default=1024, metavar='D',
                    help='dimension of hidden state per layer')
parser.add_argument('--nlayers', type=int, default=1, metavar='N',
                    help='number of layers')
parser.add_argument('--dim_d', type=int, default=512, metavar='D',
                    help='dimension of hidden state in AAE discriminator')
# Model arguments
parser.add_argument('--model_type', default='dae', metavar='M',
                    choices=['dae', 'vae', 'aae'],
                    help='which model to learn')
parser.add_argument('--lambda_kl', type=float, default=0, metavar='R',
                    help='weight for kl term in VAE')
parser.add_argument('--lambda_adv', type=float, default=0, metavar='R',
                    help='weight for adversarial loss in AAE')
parser.add_argument('--lambda_p', type=float, default=0, metavar='R',
                    help='weight for L1 penalty on posterior log-variance')
parser.add_argument('--noise', default='0,0,0,0', metavar='P,P,P,K',
                    help='word drop prob, blank prob, substitute prob'
                         'max word shuffle distance')
# Training arguments
parser.add_argument('--dropout', type=float, default=0.5, metavar='DROP',
                    help='dropout probability (0 = no dropout)')
parser.add_argument('--lr', type=float, default=0.0005, metavar='LR',
                    help='learning rate')
#parser.add_argument('--clip', type=float, default=0.25, metavar='NORM',
#                    help='gradient clipping')
parser.add_argument('--epochs', type=int, default=50, metavar='N',
                    help='number of training epochs')
parser.add_argument('--batch-size', type=int, default=256, metavar='N',
                    help='batch size')
# Others
parser.add_argument('--seed', type=int, default=1111, metavar='N',
                    help='random seed')
parser.add_argument('--no-cuda', action='store_true',
                    help='disable CUDA')
parser.add_argument('--log-interval', type=int, default=100, metavar='N',
                    help='report interval')
'''

# + colab={"base_uri": "https://localhost:8080/"} id="G3i3cj-0Up3_" outputId="fdf7d39c-2c73-4f18-9eb1-33d82dc0fbde"
NUM_EPOCHS = 1 # debugging
# !python train.py --epochs $NUM_EPOCHS --train data/yelp/train.txt --valid data/yelp/valid.txt --model_type aae --lambda_adv 10 --noise 0.3,0,0,0 --save-dir checkpoints/yelp/daae

# + colab={"base_uri": "https://localhost:8080/"} id="1mh7nfgidNdJ" outputId="da0ebbbe-2e7a-499f-af30-22169349f034"
NUM_EPOCHS = 10 # debugging
# !python train.py --epochs $NUM_EPOCHS --train data/yelp/train.txt --valid data/yelp/valid.txt --model_type aae --lambda_adv 10 --noise 0.3,0,0,0 --save-dir checkpoints/yelp/daae

# + colab={"base_uri": "https://localhost:8080/"} id="NaNeyq3ZYhe_" outputId="e3b4c7b6-e944-4d20-c48f-21f0d68765f9"
# !ls

# + colab={"base_uri": "https://localhost:8080/"} id="W_OdNhuwYlLa" outputId="0d3af920-5798-4986-9ccf-e4789456e166"
# !ls checkpoints/yelp/daae

# + id="e1Hq9eseq7dv"
from google.colab import files
#files.download('checkpoints/yelp/daae/model.pt')

# + [markdown] id="fSRiEn32rCL7"
# # Upload pretrained model

# + id="Y3AqiUXFrEcN"
from google.colab import files
#uploaded = files.upload() # store it in checkpoints/yelp/daae/model.pt

# + [markdown] id="MoCvv4mfYSA9"
# # Reconstruction

# + id="uKXVJuyxYLWD"
# !python test.py --reconstruct --data data/yelp/test.txt --output test.rec --checkpoint checkpoints/yelp/daae/

# + colab={"base_uri": "https://localhost:8080/"} id="llD_hqk7Y3Rm" outputId="791098fd-50af-4656-aead-6efd74c08dd9"
# !ls checkpoints/yelp/daae

# + colab={"base_uri": "https://localhost:8080/"} id="BzBL_6uPY3kz" outputId="7cb96ac3-8f59-4b4b-ad27-e3ea5f8ab481"
# !head checkpoints/yelp/daae/test.rec.rec

# + colab={"base_uri": "https://localhost:8080/"} id="krtESrsPZ3y_" outputId="0284615d-54d2-4a69-c34e-d67bae5fc3bd"
# !head checkpoints/yelp/daae/test.rec.z

# + colab={"base_uri": "https://localhost:8080/"} id="aVAGRBBmZ_Wo" outputId="e57cc98a-becd-42cb-e737-b3a6ca123cc5"
# !head data/yelp/test.txt

# + [markdown] id="iYP4zjFCaS2Q"
# # Sample

# + id="oRtLTTRNaEKT"
# !python test.py --sample --n 10 --output sample --checkpoint checkpoints/yelp/daae/

# + colab={"base_uri": "https://localhost:8080/"} id="yg1MEw8uaUnY" outputId="a341b76e-dfaa-4677-bdee-33ef47b5f36c"
# !ls checkpoints/yelp/daae

# + colab={"base_uri": "https://localhost:8080/"} id="Q-EF4QvYaYqz" outputId="70f0acd9-172b-4a74-e853-6a37d099a839"
# !head checkpoints/yelp/daae/sample

# + [markdown] id="sr-THLamamjI"
# # Arithmetic
#
# The difference between the average latent representation of the first two data files will be applied to the third file (separated by commas), and k denotes the scaling factor.
#

# + [markdown] id="_Tz_Y_Txg55c"
# ## Tense

# + id="Y6cqFAmxab3j"
# !python test.py --arithmetic --data data/yelp/tense/valid.past,data/yelp/tense/valid.present,data/yelp/tense/test.past --output test.past2present --checkpoint checkpoints/yelp/daae/

# + colab={"base_uri": "https://localhost:8080/"} id="UtOj8o5AbSEh" outputId="517effc9-bcd6-436e-8cfa-831e20eae74e"
# !head data/yelp/tense/valid.past

# + colab={"base_uri": "https://localhost:8080/"} id="FqwU42qvbnTP" outputId="101396ac-1b37-444e-ee6e-5c0e6310d596"
# !head data/yelp/tense/valid.present

# + colab={"base_uri": "https://localhost:8080/"} id="Sl91aiLWbql1" outputId="084def78-c9c8-4850-f1aa-b4845eca557b"
# !head data/yelp/tense/test.past

# + colab={"base_uri": "https://localhost:8080/"} id="Df37XG-xbKin" outputId="04e98445-73dc-44dd-8cbf-2568bc8c79b6"
# !head checkpoints/yelp/daae/test.past2present

# + [markdown] id="z5nbF9p_g7pQ"
# ## Sentiment

# + id="vZPQ6sZoatXK"
# !python test.py --arithmetic --k 2 --data data/yelp/sentiment/100.neg,data/yelp/sentiment/100.pos,data/yelp/sentiment/1000.neg --output 1000.neg2pos --checkpoint checkpoints/yelp/daae/

# + colab={"base_uri": "https://localhost:8080/"} id="i1o_A_3rgs79" outputId="c9d1b8a0-ec27-4a8f-8a05-545aa124c56a"
# !head data/yelp/sentiment/100.neg

# + colab={"base_uri": "https://localhost:8080/"} id="l9vw2Pwtgxlx" outputId="7dd93048-0ac3-4a0b-da35-8f7997a5db73"
# !head data/yelp/sentiment/100.pos

# + colab={"base_uri": "https://localhost:8080/"} id="xh9fTPahg19l" outputId="64c5da57-40a8-4b88-a0ca-611d1a57086b"
# !head data/yelp/sentiment/1000.neg

# + colab={"base_uri": "https://localhost:8080/"} id="Z8LiQoRZhGLo" outputId="f8c36c27-59ee-4789-be54-66a11c1003f7"
# !head checkpoints/yelp/daae/1000.neg2pos

# + [markdown] id="327Ahgmgb86B"
# # Interpolation
#
# Sentence interpolation between two data files (separated by a comma),
#

# + id="tGekWTjnb9lc"
# !python test.py --interpolate --data data/yelp/interpolate/example.long,data/yelp/interpolate/example.short --output example.int --checkpoint checkpoints/yelp/daae/

# + colab={"base_uri": "https://localhost:8080/"} id="Q3u-mKAhcbnO" outputId="63c8fd4c-3d15-4f9d-a68b-d96d8f5a1513"
# !head checkpoints/yelp/daae/example.int

# + colab={"base_uri": "https://localhost:8080/"} id="sbO3hWLIckRQ" outputId="8f22487f-fa94-4e26-c23b-543d2bb45e84"
# !head data/yelp/interpolate/example.long

# + colab={"base_uri": "https://localhost:8080/"} id="sEXD-qXIcpzw" outputId="be940779-9bf6-403b-dc68-bfc8631d06e0"
# !head data/yelp/interpolate/example.short

# + id="dqI6ngticulp"

# + [markdown] id="OrgQaMimDIrJ"
# # Optiponal: Reproduce fig 1 (toy dataset)
#
# The code below was sent to me by Tianxiao.
# It is not part of the repo.

# + [markdown] id="DSlNrC08EcBQ"
# ## Make dataset

# + id="skM4oJUGDOIv"
import os
import random

random.seed(1)

def gen(path, n=5, m=100, l=50, p=0.2):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, 'w') as f:
        for i in range(n):
            c = [random.randint(0, 1) for _ in range(l)]
            for j in range(m):
                b = c.copy()
                for k in range(l):
                    if random.random() < p:
                        b[k] = 1 - b[k]
                f.write(' '.join([str(x) for x in b]) + '\n')

gen('data/toy/data.txt')

# + [markdown] id="kUG8fRVeEd77"
# ## Train

# + id="wnW6LfqRDS38" outputId="92afa290-0781-4420-b5a3-0263396a8543" colab={"base_uri": "https://localhost:8080/"}
# !python train.py --train data/toy/data.txt --valid data/toy/data.txt --model_type aae --lambda_adv 10 --dim_z 2 --save-dir checkpoints/toy/aae/ --epochs 1

# + id="As6Q8UsbDT1m" outputId="04f373f9-6038-406f-f144-84b34f485f21" colab={"base_uri": "https://localhost:8080/"}
# !python train.py --train data/toy/data.txt --valid data/toy/data.txt --model_type dae --lambda_adv 10 --dim_z 2 --noise 0,0,0.2,0 --save-dir checkpoints/toy/daae/ --epochs 1

# + id="BMqllw1KEQdL" outputId="6f95b32b-4fb2-4663-da21-2d2613afa3af" colab={"base_uri": "https://localhost:8080/"}
# !ls checkpoints/toy/aae

# + [markdown] id="I93ajRDCEf-N"
# ## Compute latent representations

# + id="OTURry3wEhoB"
# !python test.py --reconstruct --data data/toy/data.txt --output data --max-len 55 --checkpoint checkpoints/toy/aae/

# + id="36Oh5lewEnmy"
# !python test.py --reconstruct --data data/toy/data.txt --output data --max-len 55 --checkpoint checkpoints/toy/daae/

# + [markdown] id="O3jHgjW4EkUj"
# ## Plot

# + id="oq8lP-8_DyoR"
import sys
import numpy as np
import matplotlib.pyplot as plt
#from sklearn.manifold import TSNE

def plot_z(filename):
  x = []
  with open(filename) as f:
      for line in f:
          parts = line.split()
          x.append([float(p) for p in parts])
  x = np.array(x)
  #x = TSNE().fit_transform(x)

  n, m = 5, 100
  for i in range(n):
      l, r = i*m, (i+1)*m
      plt.scatter(x[l:r, 0], x[l:r, 1])

  #plt.title('DAAE', fontsize=22)
  plt.xticks(fontsize=18)
  plt.yticks(fontsize=18)
  plt.show()

# + id="SZ3tcCrPEFhT" outputId="704aae9b-928b-4917-ba76-fdd6d05c0529" colab={"base_uri": "https://localhost:8080/", "height": 279}
plot_z('checkpoints/toy/aae/data.z')

# + id="1dKqBy9ZELE4" outputId="d13fdc09-04cf-42ca-f770-fe08de7565ab" colab={"base_uri": "https://localhost:8080/", "height": 273}
plot_z('checkpoints/toy/daae/data.z')

# + id="PLGYhD9uEuRt"


from __future__ import annotations

from typing import Any, Optional, Iterator, Dict

from collections.abc import Mapping, MutableMapping

from ..exceptions import ValidationError
from ..base_schema import SchemaAnything

from .DOMElement import DOMElement
from . import DOMInfo
from .DOMProperties import DOMProperties
from .functions import document, schema

class DOMObject(DOMElement, MutableMapping):
    """
    An object with named properties.
    """

    __json_schema_properties__: DOMProperties = None
    __json_element_data__: Dict[str, Optional[DOMElement]] = None

    def __init__(
        self, value: Mapping[str, Any] = None, json_dom_info: DOMInfo = None
    ) -> None:
        """
        :param value:         A dict (or any :class:`collections.abc.Mapping`) containing the data to populate this
                              object's properties.
        :param json_dom_info: A :class:`~wysdom.dom.DOMInfo` named tuple containing information about this object's
                              position in the DOM.
        """
        if value and not isinstance(value, Mapping):
            raise ValidationError(
                f"Cannot validate input. Object is not a mapping: {value}"
            )
        schema(self).validate(value)
        super().__init__(None, json_dom_info)
        self.__json_element_data__ = {}
        try:
            for key, value in value.items():
                self[key] = value
        except KeyError as e:
            raise ValidationError(str(e))

    def __getitem__(self, key: str) -> Optional[DOMElement]:
        return self.__json_element_data__[key]

    def __setitem__(self, key: str, value: Optional[DOMElement]) -> None:
        if value is None:
            if key in self.__json_schema_properties__.required:
                raise ValueError(
                    f"The property '{key}' is not optional and cannot be None."
                )
            self.__json_element_data__[key] = None
        else:
            item_class = self.__json_schema_properties__.properties.get(
                key, self.__json_schema_properties__.additional_properties
            )
            if item_class is True:
                item_class = SchemaAnything()
            if not item_class:
                raise KeyError(
                    f"No property named '{key}' exists, and "
                    "additional properties are not allowed."
                )
            self.__json_element_data__[key] = item_class(
                value, DOMInfo(document=document(self), parent=self, element_key=key)
            )

    def __delitem__(self, key: str) -> None:
        del self.__json_element_data__[key]

    def __len__(self) -> int:
        return len(self.__json_element_data__)

    def __iter__(self) -> Iterator[str]:
        return iter(self.__json_element_data__)

    def __repr__(self):
        return f"{self.__class__.__name__}({repr(self.__json_element_data__)})"

    def __str__(self):
        return str(self.__json_element_data__)

    def walk_elements(self) -> Iterator[DOMInfo]:
        yield self.__json_dom_info__
        for key, value in self.items():
            if isinstance(value, DOMElement):
                yield from value.walk_elements()
            else:
                yield DOMInfo(value, document(self), self, key)

    def to_builtin(self) -> Dict[str, Any]:
        """
        Returns the contents of this DOM object as a Python builtin.

        :return: A Python dict containing this object's data
        """
        return {k: self._value_to_builtin(v) for k, v in self.items()}

    def __copy__(self) -> DOMObject:
        cls = self.__class__
        result = cls.__new__(cls)
        super(DOMObject, result).__init__(json_dom_info=self.__json_dom_info__)
        result.__json_element_data__ = dict(self.__json_element_data__)
        return result

    def __deepcopy__(self, memo: Dict[int, DOMElement]) -> DOMObject:
        cls = self.__class__
        result = cls(value=self.to_builtin(), json_dom_info=self.__json_dom_info__)
        memo[id(self)] = result
        return result


import common.cv as cc
import common.graph as cg
import csv

# Annotated positions for precision/recall tests
def get_annotated_poses(image_file):
    annotated_nodes = get_annotated_nodes(image_file)
    annotated_poses = [node.pos for node in annotated_nodes]

    return annotated_poses

def get_annotated_nodes(image_file):
    annotated_file = open("graphs/annotated/" + image_file[4:8] + ".gdf")
    annotated_graph = cg.translate_graph(annotated_file.read().splitlines()[1:])

    return annotated_graph.nodes

def get_generated_poses(model):
    poses = []
    for tup in model:
        for keylabel in tup:
            kp,label = keylabel
            poses.append(cc.get_point_tuple(kp))

    return list(set(poses))

def get_label_positions(model, label):
    label_positions = []
    for tup in model:
        for keylabel in tup:
            kp,found_label = keylabel
            if found_label.name == label:
                label_positions.append(cc.get_point_tuple(kp))

    return list(set(label_positions))

def get_precision(annotated_poses, model_poses):
    tp = len(set(annotated_poses).intersection(model_poses))

    if len(model_poses) == 0:
        return 0

    return tp / len(model_poses)

def get_recall(annotated_poses, model_poses):
    tp = len(set(annotated_poses).intersection(model_poses))

    if len(annotated_poses) == 0 or tp == 0:
        return len(annotated_poses)

    return tp / len(annotated_poses)

def get_precision_recall(annotated_poses, model_poses):
    precision = get_precision(annotated_poses, model_poses)
    recall = get_recall(annotated_poses, model_poses)

    return (precision,recall)

def get_classification_metrics(annotated_poses, poses):
    tp = len(set(annotated_poses).intersection(poses))
    fp = len(poses)
    fn = len(annotated_poses)

    return (tp,fp,fn)

def update_dictionary(key, data, dictionary):
    if key in dictionary:
        total = dictionary[key]
        dictionary[key] = tuple(sum(x) for x in zip(total,data))
    else:
        dictionary[key] = data

def experiment_identification(image_file, method, model_category, best_model, experiment_dict):
    actual_category = "juvenile" if image_file[4] == "4" else "mature"
    annotated_poses = get_annotated_poses(image_file)
    poses = get_generated_poses(best_model)

    key = (method,model_category,actual_category)
    data = get_classification_metrics(annotated_poses, poses)
    update_dictionary(key, data, experiment_dict)

def experiment_label(image_file, method, model_category, label, best_model, experiment_dict):
    actual_category = "juvenile" if image_file[4] == "4" else "mature"
    annotated_nodes = get_annotated_nodes(image_file)
    filtered_nodes = [node.pos for node in annotated_nodes if node.label == label]
    poses = get_label_positions(best_model, label)

    key = (method,label,model_category,actual_category)
    data = get_classification_metrics(filtered_nodes, poses)
    update_dictionary(key, data, experiment_dict)

def write_experiment(csv_file, experiment_dict):
    writer = csv.writer(csv_file, delimiter=",")

    for key,data in experiment_dict.items():
        headers = list(key)
        tp,fp,fn = data

        precision = tp/fp
        recall = tp/fn

        writer.writerow(headers + [precision, recall])
        csv_file.flush()


from django.db.transaction import atomic
from rest_framework.filters import SearchFilter
from rest_framework.generics import ListAPIView, RetrieveAPIView, RetrieveUpdateAPIView
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView

from job_posting.models import (
    Department,
    Division,
    ZonalLab,
    QualificationMaster,
    PositionQualificationMapping,
    JobPostingRequirement,
    JobPosting,
    SelectionProcessContent,
    ServiceConditions,
    UserJobPositions,
    AppealMaster,
    NewPositionMaster,
    PermanentPositionMaster,
    TemporaryPositionMaster,
    QualificationJobHistoryMaster,
    FeeMaster,
)
from job_posting.serializer import (
    DepartmentSerializer,
    DivisionSerializer,
    ZonalLabSerializer,
    QualificationMasterSerializer,
    ProjectApprovalListSerializer,
    PositionQualificationMappingSerializer,
    JobTemplateSerializer,
    JobPostingSerializer,
    SelectionProcessContentSerializer,
    ServiceConditionsSerializer,
    UserJobPositionsSerializer,
    ProjectRequirementSerializer,
    UserAppealForJobPositionsSerializer,
    AppealReasonMasterSerializer,
    NewPositionMasterSerializer,
    PermanentPositionMasterSerializer,
    TemporaryPositionMasterSerializer,
    ProjectRequirementApprovalStatusSerializer,
    QualificationJobHistoryMasterSerializer,
    PublicJobPostSerializer,
)

from rest_framework import status
from rest_framework.response import Response

from user.models import UserDocuments

class QualificationMasterSearchListView(ListAPIView):
    queryset = QualificationMaster.objects.all()
    serializer_class = QualificationMasterSerializer
    filter_backends = [SearchFilter]
    search_fields = ("qualification_id", "qualification", "short_code")

class QualificationJobHistoryMasterSearchListView(ListAPIView):
    queryset = QualificationJobHistoryMaster.objects.all()
    serializer_class = QualificationJobHistoryMasterSerializer
    filter_backends = [SearchFilter]
    search_fields = ("qualification_job_id", "qualification", "short_code")

class RetrieveQualificationMasterView(APIView):
    def get(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        qual = QualificationMaster.objects.get(qualification_id=id, is_deleted=False)
        serializer = QualificationMasterSerializer(qual)
        return Response(serializer.data, status=200)

class DeleteQualificationMasterView(APIView):
    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            qualification = QualificationMaster.objects.get(qualification_id=id)
            qualification.is_deleted = True
            qualification.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

class UpdateQualificationMasterView(APIView):
    def put(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        qualification = QualificationMaster.objects.get(qualification_id=id)
        data = self.request.data
        serializer = QualificationMasterSerializer(qualification, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=qualification, validated_data=data)
        return Response(serializer.data, status=200)

class CreateQualificationMasterView(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = QualificationMasterSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=200)

class QualificationMasterListView(APIView):
    def get(self, request, *args, **kwargs):
        docs = QualificationMaster.objects.filter(is_deleted=False).order_by('qualification')
        serializer = QualificationMasterSerializer(docs, many=True)
        return Response(serializer.data, status=200)

# Qualification Job History

class QualificationJobHistoryMasterView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            qualification_job_id = self.kwargs["id"]
            if QualificationJobHistoryMaster.objects.filter(
                qualification_job_id=qualification_job_id, is_deleted=False
            ).exists():
                qual = QualificationJobHistoryMaster.objects.get(
                    qualification_job_id=qualification_job_id, is_deleted=False
                )
                serializer = QualificationJobHistoryMasterSerializer(qual)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"message": "Details Not Found."}, status=401)
        except:
            docs = QualificationJobHistoryMaster.objects.filter(is_deleted=False).order_by('qualification')
            serializer = QualificationJobHistoryMasterSerializer(docs, many=True)
            return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            qualification = QualificationJobHistoryMaster.objects.get(
                qualification_job_id=id
            )
            qualification.is_deleted = True
            qualification.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

    def put(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        qualification = QualificationJobHistoryMaster.objects.get(
            qualification_job_id=id
        )
        data = self.request.data
        serializer = QualificationJobHistoryMasterSerializer(qualification, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=qualification, validated_data=data)
        return Response(serializer.data, status=200)

    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = QualificationJobHistoryMasterSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=200)

class DepartmentListView(APIView):
    def get(self, request, *args, **kwargs):
        if Department.objects.filter(is_deleted=False).count() > 0:
            departments = Department.objects.filter(is_deleted=False)
            serializer = DepartmentSerializer(departments, many=True)
            return Response(serializer.data, status=200)
        else:
            return Response(data={"messege": "No Records found"}, status=404)

class DivisionListView(APIView):
    def get(self, request, *args, **kwargs):
        try:
            division_id = self.kwargs["id"]
            divisions = Division.objects.get(division_id=division_id, is_deleted=False)
            serializer = DivisionSerializer(divisions)
            return Response(serializer.data, status=200)
        except:
            if Division.objects.filter(is_deleted=False).count() > 0:
                divisions = Division.objects.filter(is_deleted=False).order_by('division_name')
                serializer = DivisionSerializer(divisions, many=True)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"message": "No Records found"}, status=404)

    # class DeleteDivisionMasterView(APIView):
    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            division = Division.objects.get(division_id=id)
            division.is_deleted = True
            division.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

    # class UpdateDivisionMasterView(APIView):
    def put(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        division = Division.objects.get(division_id=id)
        data = self.request.data
        serializer = DivisionSerializer(division, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=division, validated_data=data)
        return Response(serializer.data, status=200)

    # class CreateDivisionMasterView(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = DivisionSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=200)

class ZonalLabListView(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = ZonalLabSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=200)

    def get(self, request, *args, **kwargs):
        try:
            lab_id = self.kwargs["id"]
            labs = ZonalLab.objects.get(zonal_lab_id=lab_id, is_deleted=False)
            serializer = ZonalLabSerializer(labs)
            return Response(serializer.data, status=200)
        except:
            if ZonalLab.objects.filter(is_deleted=False).count() > 0:
                labs = ZonalLab.objects.filter(is_deleted=False).order_by('zonal_lab_name')
                serializer = ZonalLabSerializer(labs, many=True)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"messege": "No Records found"}, status=404)

    def put(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        labs = ZonalLab.objects.get(zonal_lab_id=id)
        data = self.request.data
        serializer = ZonalLabSerializer(labs, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=labs, validated_data=data)
        return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            labs = ZonalLab.objects.get(zonal_lab_id=id)
            labs.is_deleted = True
            labs.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

class ProjectApprovalListView(APIView):
    def get(self, request, *args, **kwargs):
        req = JobPostingRequirement.objects.filter(is_deleted=False)
        serializer = ProjectApprovalListSerializer(req, many=True)
        return Response(serializer.data, status=200)

class ProjectApprovalStatusListView(APIView):
    def get(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        if JobPostingRequirement.objects.filter(id=id, is_deleted=False).exists():
            job = JobPostingRequirement.objects.get(id=id, is_deleted=False)
            serializer = ProjectRequirementApprovalStatusSerializer(job)
            return Response(serializer.data, status=200)
        else:
            return Response(data={"message": "Details Not Found."}, status=401)

    def put(self, request, *args, **kwargs):
        data = self.request.data
        id = self.kwargs["id"]
        project = JobPostingRequirement.objects.get(id=id, is_deleted=False)
        serializer = ProjectRequirementApprovalStatusSerializer(project, data=data)
        serializer.is_valid(raise_exception=True)
        result = serializer.update(instance=project, validated_data=data)
        print("result=========", result)
        project = JobPostingRequirement.objects.get(id=result)
        serializer = ProjectRequirementApprovalStatusSerializer(project)
        return Response(serializer.data, status=200)

# project Requirement

class UpdateProjectRequirementView(APIView):
    def put(self, request, *args, **kwargs):
        data = self.request.data
        id = self.kwargs["id"]
        project = JobPostingRequirement.objects.get(id=id, is_deleted=False)
        serializer = ProjectRequirementSerializer(project, data=data)
        serializer.is_valid(raise_exception=True)
        result = serializer.update(instance=project, validated_data=data)
        project = JobPostingRequirement.objects.get(id=result)
        serializer = ProjectRequirementSerializer(project)
        return Response(serializer.data, status=200)

class CreateProjectRequirementView(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = ProjectRequirementSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        result = serializer.save(validated_data=data)
        job_posting = JobPostingRequirement.objects.get(id=result)
        serializer = ProjectRequirementSerializer(job_posting)
        return Response(serializer.data, status=200)

class DeleteProjectRequirementView(APIView):
    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            project = JobPostingRequirement.objects.get(id=id)
            project.is_deleted = True
            project.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

class ProjectRequirementListView(APIView):
    def get(self, request, *args, **kwargs):
        job = JobPostingRequirement.objects.filter(is_deleted=False)
        serializer = ProjectRequirementSerializer(job, many=True)
        return Response(serializer.data, status=200)

class ProjectApprovalFilterListView(ListAPIView):
    queryset = JobPostingRequirement.objects.all()
    serializer_class = ProjectRequirementSerializer
    filterset_fields = [
        "division_name__division_name",
        "zonal_lab__zonal_lab_name",
        "project_number",
        "status",
        "manpower_position__position",
        "project_start_date",
        "project_end_date",
    ]

class ProjectApprovalSearchListView(ListAPIView):
    queryset = JobPostingRequirement.objects.all()
    serializer_class = ProjectRequirementSerializer
    filter_backends = [SearchFilter]
    search_fields = ("project_title", "job_requirements", "desired_qualification")

class RetrieveProjectRequirementView(APIView):
    def get(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        if JobPostingRequirement.objects.filter(id=id, is_deleted=False).exists():
            job = JobPostingRequirement.objects.get(id=id, is_deleted=False)
            serializer = ProjectRequirementSerializer(job)
            return Response(serializer.data, status=200)
        else:
            return Response(data={"message": "Details Not Found."}, status=401)

class PositionQualificationMappingListView(APIView):
    def get(self, request, *args, **kwargs):
        projects = PositionQualificationMapping.objects.filter(is_deleted=False)
        serializer = PositionQualificationMappingSerializer(projects, many=True)
        return Response(serializer.data, status=200)

class JobTemplateCreateView(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        for template_data in data:
            serializer = JobTemplateSerializer(data=template_data)
            serializer.is_valid(raise_exception=True)
            serializer.save(validated_data=template_data)
        return Response(data={"message": "Template Saved Successfully"}, status=200)

    # def get(self, request, *args, **kwargs):
    #     projects = JobTemplate.objects.filter(is_deleted=False)
    #     serializer = JobTemplateSerializer(projects, many=True)
    #     return Response(serializer.data, status=200)

class JobPostingCreateView(APIView):
    @atomic
    def post(self, request, *args, **kwargs):
        try:
            data = self.request.data
            serializer = JobPostingSerializer(data=data)
            if serializer.is_valid():
                result = serializer.save(validated_data=data)
                job_posting = JobPosting.objects.get(job_posting_id=result)
                serializer = JobPostingSerializer(job_posting)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"errors": serializer.errors})
        except Exception as e:
            return Response(data={"errors": str(e)})

class JobPostingDetailView(RetrieveUpdateAPIView):
    queryset = JobPosting.objects.filter(is_deleted=False)
    serializer_class = JobPostingSerializer
    lookup_field = "job_posting_id"
    lookup_url_kwarg = "id"

    @atomic
    def put(self, request, *args, **kwargs):
        data = self.request.data
        job_posting_id = self.kwargs["id"]
        job_posting = JobPosting.objects.get(job_posting_id=job_posting_id)
        serializer = JobPostingSerializer(job_posting, data=data)
        if serializer.is_valid():
            return Response(
                data=serializer.update(job_posting, validated_data=data), status=200
            )
        else:
            return Response(data={"errors": serializer.errors})

class GetSelectionContent(APIView):
    def get(self, request, *args, **kwargs):
        # position_name_list = []
        # Todo: #Imagine you will get list of selected positions(Position_names) for the job
        # queryset = SelectionProcessContent.objects.none()
        # for i in position_name_list:
        #     if SelectionProcessContent.objects.filter(description__icontains=i):
        #         queryset |= SelectionProcessContent.objects.filter(description__icontains=i)
        #
        # serializer = SelectionProcessContentSerializer(queryset,many=True)

        # For now sending all records
        process_content = SelectionProcessContent.objects.filter(is_deleted=False)
        serializer = SelectionProcessContentSerializer(process_content, many=True)
        return Response(serializer.data, status=200)

class GetServiceConditions(APIView):
    def get(self, request, *args, **kwargs):
        conditions = ServiceConditions.objects.filter(is_deleted=False)
        serializer = ServiceConditionsSerializer(conditions, many=True)
        return Response(serializer.data, status=200)

# Filtering on Position, Experience, Job Requirements, Status

class JobPostingSearchListView(ListAPIView):
    queryset = JobPosting.objects.filter(is_deleted=False)
    serializer_class = JobPostingSerializer
    filter_backends = [SearchFilter]
    search_fields = ("notification_id", "notification_title", "status")

class JobPostingFilterListView(ListAPIView):
    queryset = JobPosting.objects.filter(is_deleted=False)
    serializer_class = JobPostingSerializer
    filterset_fields = ["status"]

class JobPostingListView(ListAPIView):
    queryset = JobPosting.objects.prefetch_related("job_posting_applicants").filter(
        is_deleted=False
    )
    serializer_class = JobPostingSerializer
    filterset_fields = ["job_type", "status"]

class PublicJobPostingView(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = PublicJobPostSerializer
    queryset = JobPosting.objects.filter(is_deleted=False)

class PublicJobPostingFilterListView(ListAPIView):
    permission_classes = (AllowAny,)
    queryset = JobPosting.objects.filter(is_deleted=False)
    serializer_class = PublicJobPostSerializer
    filterset_fields = ["description", "publication_date", "end_date"]

class PublicJobPostingSearchListView(ListAPIView):
    permission_classes = (AllowAny,)
    serializer_class = PublicJobPostSerializer
    queryset = JobPosting.objects.filter(is_deleted=False)
    filter_backends = [SearchFilter]
    search_fields = (
        "pre_ad_description",
        "post_ad_description",
    )

class ApplicantJobPositions(RetrieveAPIView):
    permission_classes = (AllowAny,)
    serializer_class = PublicJobPostSerializer
    queryset = JobPosting.objects.filter(is_deleted=False)
    lookup_field = "job_posting_id"
    lookup_url_kwarg = "id"

class ApplicationCountByJobPositions(APIView):
    def get(self, request, *args, **kwargs):
        job_posting_id = self.kwargs["id"]
        try:
            if UserJobPositions.objects.filter(
                job_posting__job_posting_id=job_posting_id, is_deleted=False
            ).exists():
                applicant_count = UserJobPositions.objects.filter(
                    job_posting__job_posting_id=job_posting_id, is_deleted=False
                ).count()
                print("applicants---------->", applicant_count)
                return Response(applicant_count, status=200)
            else:
                return Response(
                    data={"message": "No Application for this job..."},
                    status=200,
                )
        except:
            return Response(
                data={"message": "No Application for this job..."},
                status=200,
            )

class ApplicantListByJobPositions(APIView):
    def get(self, request, *args, **kwargs):
        try:
            job_posting_id = self.kwargs["id"]
            applicants = UserJobPositions.objects.prefetch_related(
                "user", "user__user_profile", "job_posting", "position"
            ).filter(job_posting__job_posting_id=job_posting_id, is_deleted=False)
            serializer = UserJobPositionsSerializer(applicants, many=True)
            return Response(serializer.data, status=200)
        except:
            applicants = UserJobPositions.objects.filter(is_deleted=False)
            serializer = UserJobPositionsSerializer(applicants, many=True)
            return Response(serializer.data, status=200)

class ApproveRejectApplicantView(RetrieveUpdateAPIView):
    queryset = UserJobPositions.objects.all()
    serializer_class = UserJobPositionsSerializer
    lookup_url_kwarg = "id"

    @atomic
    def put(self, request, *args, **kwargs):
        data = self.request.data
        application_id = self.kwargs["id"]
        print("data------------->", data)
        try:
            applicant = UserJobPositions.objects.get(id=application_id)
            # for status_data in data:
            print("status_data------------->", data["status"])
            print(
                "applicant.applied_job_status == data['status']------------->",
                applicant.applied_job_status,
                data["status"],
            )

            if data["status"] == "rejected" and applicant.applied_job_status:
                serializer = UserJobPositionsSerializer(applicant, data=data)
                serializer.is_valid(raise_exception=True)  # approve/reject/draft
                serializer.update(applicant, validated_data=data)
                return Response(serializer.data, status=200)
            elif data["status"] == "accepted" and applicant.applied_job_status:
                serializer = UserJobPositionsSerializer(applicant, data=data)
                serializer.is_valid(raise_exception=True)  # approve/reject/draft
                serializer.update(applicant, validated_data=data)
                return Response(serializer.data, status=200)
            elif data["status"] == "awaiting review" and applicant.applied_job_status:
                serializer = UserJobPositionsSerializer(applicant, data=data)
                serializer.is_valid(raise_exception=True)  # approve/reject/draft
                serializer.update(applicant, validated_data=data)
                return Response(serializer.data, status=200)
            else:
                return Response(
                    data={"message": "Please select a valid job status."},
                    status=200,
                )
        except:
            return Response(data={"message": "Detail not found"}, status=401)

class ApproveRejectApplicantForJobPositions(APIView):
    def put(self, request, *args, **kwargs):
        data = self.request.data
        appeal_id = self.kwargs["id"]
        try:
            applicants = UserJobPositions.objects.get(id=appeal_id)
            if applicants.applied_job_status == "rejected":
                applicants.appealed = True
                applicants.save()
                serializer = UserAppealForJobPositionsSerializer(applicants, data=data)
                serializer.is_valid(raise_exception=True)
                serializer.update(applicants, validated_data=data)
                return Response(serializer.data, status=200)
            else:
                return Response(
                    data={"message": "You've already appealed for this job..."},
                    status=200,
                )
        except:
            return Response(
                data={"message": "you are not eligible for the appeal..."}, status=401
            )

class UserAppealForJobPositions(APIView):
    def put(self, request, *args, **kwargs):
        data = self.request.data
        appeal_id = self.kwargs["id"]
        applicants = UserJobPositions.objects.get(id=appeal_id)
        if applicants.applied_job_status == "rejected":
            applicants.applied_job_status = "appealed"
            applicants.save()
            serializer = UserAppealForJobPositionsSerializer(applicants, data=data)
            serializer.is_valid(raise_exception=True)
            serializer.update(applicants, validated_data=data)
            return Response(serializer.data, status=200)
        if applicants.applied_job_status == "appealed":
            return Response(
                data={"message": "You've already appealed for this job..."},
                status=200,
            )
        else:
            return Response(
                data={"message": "you are not eligible for the appeal..."},
                status=200,
            )

class AppealReasonMasterViews(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        serializer = AppealReasonMasterSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=200)

    def get(self, request, *args, **kwargs):
        try:
            appeal_id = self.kwargs["id"]
            applicant = AppealMaster.objects.get(appeal_id=appeal_id, is_deleted=False)
            serializer = AppealReasonMasterSerializer(applicant)
            return Response(serializer.data, status=200)
        except:
            applicants = AppealMaster.objects.filter(is_deleted=False)
            serializer = AppealReasonMasterSerializer(applicants, many=True)
            return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            appeal_id = self.kwargs["id"]
            applicant = AppealMaster.objects.get(appeal_id=appeal_id)
            applicant.is_deleted = True
            applicant.save()
            return Response(
                data={"message": "Record Deleted Successfully(Soft Delete)."},
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

    def put(self, request, *args, **kwargs):
        appeal_id = self.kwargs["id"]
        applicant = AppealMaster.objects.get(appeal_id=appeal_id)
        data = self.request.data
        serializer = AppealReasonMasterSerializer(applicant, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=applicant, validated_data=data)
        return Response(serializer.data, status=200)

# NewPositionMaster
class NewPositionMasterViews(APIView):
    def post(self, request, *args, **kwargs):
        data = self.request.data
        print("data ------->", data)
        serializer = NewPositionMasterSerializer(data=data)
        print("serializer ----------->", serializer)
        serializer.is_valid(raise_exception=True)
        result = serializer.save(validated_data=data)
        print("result ----------->", result)
        posi = NewPositionMaster.objects.get(position_id=result)
        serializer = NewPositionMasterSerializer(posi)
        return Response(serializer.data, status=200)

    def get(self, request, *args, **kwargs):
        try:
            position_id = self.kwargs["id"]
            if NewPositionMaster.objects.filter(
                position_id=position_id, is_deleted=False
            ).exists():
                position = NewPositionMaster.objects.get(
                    position_id=position_id, is_deleted=False
                )
                serializer = NewPositionMasterSerializer(position)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"message": "Details Not Found."}, status=401)
        except:
            positions = NewPositionMaster.objects.filter(is_deleted=False)
            serializer = NewPositionMasterSerializer(positions, many=True)
            return Response(serializer.data, status=200)

    def put(self, request, *args, **kwargs):
        id = self.kwargs["id"]
        posi = NewPositionMaster.objects.get(position_id=id)
        data = self.request.data
        serializer = NewPositionMasterSerializer(posi, data=data)
        serializer.is_valid(raise_exception=True)
        serializer.update(instance=posi, validated_data=data)
        return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            posi = NewPositionMaster.objects.get(position_id=id)
            posi.is_deleted = True
            posi.save()
            return Response(
                data={
                    "message": "ManPower Position Deleted Successfully(Soft Delete)."
                },
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

# Permanent Position
class PermanentPositionMasterFilterListView(ListAPIView):
    queryset = PermanentPositionMaster.objects.all()
    serializer_class = PermanentPositionMasterSerializer
    filterset_fields = [
        "perm_position_master__position_name",
        "perm_position_master__position_display_name",
        "perm_position_master__qualification",
        "perm_position_master__qualification_job_history",
        "grade",
        "level",
    ]

class PermanentPositionMasterSearchListView(ListAPIView):
    queryset = PermanentPositionMaster.objects.all()
    serializer_class = PermanentPositionMasterSerializer
    filter_backends = [SearchFilter]
    search_fields = (
        "perm_position_master__qualification__qualification",
        "perm_position_master__qualification_desc",
    )

class PermanentPositionMasterViews(APIView):
    def get(self, request, *args, **kwargs):
        try:
            position_id = self.kwargs["id"]
            if PermanentPositionMaster.objects.filter(
                perm_position_id=position_id, is_deleted=False
            ).exists():
                position = PermanentPositionMaster.objects.get(
                    perm_position_id=position_id, is_deleted=False
                )
                serializer = PermanentPositionMasterSerializer(position)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"message": "Details Not Found."}, status=401)
        except:
            positions = PermanentPositionMaster.objects.filter(is_deleted=False).order_by('perm_position_master__position_name')
            serializer = PermanentPositionMasterSerializer(positions, many=True)
            return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            info = PermanentPositionMaster.objects.get(perm_position_id=id)
            info.is_deleted = True
            info.save()
            return Response(
                data={
                    "message": "Permanent Position Deleted Successfully(Soft Delete)."
                },
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

    def put(self, request, *args, **kwargs):
        data = self.request.data
        id = self.kwargs["id"]
        try:
            info = PermanentPositionMaster.objects.get(
                perm_position_id=id, is_deleted=False
            )
            print("info ------->", info)

            serializer = PermanentPositionMasterSerializer(info, data=data)
            serializer.is_valid(raise_exception=True)
            result = serializer.update(instance=info, validated_data=data)
            print("result ------->", result)

            info = PermanentPositionMaster.objects.get(perm_position_id=result)
            print("info after------->", info)

            serializer = PermanentPositionMasterSerializer(info)
            print("serializer ------->", serializer.data)

            return Response(serializer.data, status=200)
        except Exception as e:
            return Response(data={"errors": str(e)})

    def post(self, request, *args, **kwargs):
        try:
            data = self.request.data
            print("data ------->", data)
            serializer = PermanentPositionMasterSerializer(data=data)
            print("serializer ----------->", serializer)
            serializer.is_valid(raise_exception=True)
            result = serializer.save(validated_data=data)
            print("result ----------->", result)
            posi = PermanentPositionMaster.objects.get(perm_position_id=result)
            serializer = PermanentPositionMasterSerializer(posi)
            return Response(serializer.data, status=200)
        except Exception as e:
            return Response(data={"errors": str(e)})

# Temporary Position
class TemporaryPositionMasterFilterListView(ListAPIView):
    queryset = TemporaryPositionMaster.objects.filter(is_deleted=False)
    serializer_class = TemporaryPositionMasterSerializer
    filterset_fields = [
        "temp_position_master__position_name",
        "temp_position_master__position_display_name",
        "temp_position_master__qualification",
        "temp_position_master__qualification_job_history",
        "salary",
        "allowance",
    ]

class TemporaryPositionMasterSearchListView(ListAPIView):
    queryset = TemporaryPositionMaster.objects.filter(is_deleted=False)
    serializer_class = TemporaryPositionMasterSerializer
    filter_backends = [SearchFilter]
    search_fields = (
        "temp_position_master__qualification__qualification",
        "temp_position_master__qualification_desc",
    )

class TemporaryPositionMasterViews(APIView):
    def get(self, request, *args, **kwargs):
        try:
            position_id = self.kwargs["id"]
            if TemporaryPositionMaster.objects.filter(
                temp_position_id=position_id, is_deleted=False
            ).exists():
                position = TemporaryPositionMaster.objects.get(
                    temp_position_id=position_id, is_deleted=False
                )
                serializer = TemporaryPositionMasterSerializer(position)
                return Response(serializer.data, status=200)
            else:
                return Response(data={"message": "Details Not Found."}, status=401)
        except:
            positions = TemporaryPositionMaster.objects.filter(is_deleted=False).order_by('temp_position_master__position_name')
            serializer = TemporaryPositionMasterSerializer(positions, many=True)
            return Response(serializer.data, status=200)

    def delete(self, request, *args, **kwargs):
        try:
            id = self.kwargs["id"]
            info = TemporaryPositionMaster.objects.get(temp_position_id=id)
            info.is_deleted = True
            info.save()
            return Response(
                data={
                    "message": "Temporary Position Deleted Successfully(Soft Delete)."
                },
                status=200,
            )
        except:
            return Response(data={"message": "Details Not Found."}, status=401)

    def put(self, request, *args, **kwargs):
        data = self.request.data
        id = self.kwargs["id"]
        try:
            info = TemporaryPositionMaster.objects.get(
                temp_position_id=id, is_deleted=False
            )
            print("info ------->", info)
            serializer = TemporaryPositionMasterSerializer(info, data=data)
            serializer.is_valid(raise_exception=True)
            result = serializer.update(instance=info, validated_data=data)
            print("result ------->", result)
            info = TemporaryPositionMaster.objects.get(temp_position_id=result)
            print("info after------->", info)

            serializer = TemporaryPositionMasterSerializer(info)
            print("serializer ------->", serializer.data)

            return Response(serializer.data, status=200)
        except Exception as e:
            return Response(data={"errors": str(e)})

    def post(self, request, *args, **kwargs):
        try:
            data = self.request.data
            print("data ------->", data)
            serializer = TemporaryPositionMasterSerializer(data=data)
            print("serializer ----------->", serializer)
            serializer.is_valid(raise_exception=True)
            result = serializer.save(validated_data=data)
            print("result ----------->", result)
            posi = TemporaryPositionMaster.objects.get(temp_position_id=result)
            serializer = TemporaryPositionMasterSerializer(posi)
            return Response(serializer.data, status=200)
        except Exception as e:
            return Response(data={"errors": str(e)})


from aiogram import types
from aiogram.dispatcher.filters.builtin import CommandHelp

from loader import dp
from utils.misc import rate_limit

@rate_limit(5, 'help')
@dp.message_handler(CommandHelp())
async def bot_help(message: types.Message):
    text = [
        'Список команд: ',
        '/start - Начать диалог',
        '/help - Получить справку',
        '/callback - Перезвонить',
        '/show_on_map - Показать на карте',
    ]
    await message.answer('\n'.join(text))


import numpy as np
from numpy.random import Generator
from sympy import lambdify

class PointsGen:

    def __init__(self, rng: Generator):
        self.rng = rng

    def mk_points(self, num: int, sympy_expr):

        free_vars = list(sympy_expr.free_symbols)
        # sort variables by name
        free_vars = sorted(free_vars, key=lambda v: int(v.name[1:]))

        inps = self.rng.random((len(free_vars), num))
        f = lambdify(free_vars, sympy_expr, "numpy")
        out = f(*inps)

        points = np.row_stack((out, inps))
        return points


from itertools import product
import numpy as np
import skimage.color

_FREQS = np.arange(0.05, 0.30, 0.1)
_SIGMAS = range(1, 21, 7)
_THETAS = np.arange(0, np.pi, 0.25*np.pi)

def add_channels(img, colorspace='rgb',
                 methods=['gabor', 'gaussian', 'sobel'],
                 methods_params=None):
    '''Add artificial channels to an image

    Parameters
    ----------
    img : np.ndarray
        NxMx3 array with colored image data
    colorspace : str, optional
        String indicating colorspace of *img* (rgb/hsv/etc.)
    methods : list, optional
        List of strings indicating channels to be added
    methods_params : dict, optional
        Dictionairy with named options for channel functions

    Notes
    -----
    Currently implemented channels are:
    * gabor, with options *frequencies* and *thetas*
    * gaussian, with option *sigmas*
    * sobel, without any options

    Returns
    -------
    np.ndarray
        NxMx(3+P) array with image data with extra channels where P
        is the number of channels added
    '''

    if colorspace.lower() == 'rgb':
        gray = img.mean(-1)
    elif colorspace.lower() == 'hsv':
        gray = img[..., -1]
    else:
        raise ValueError(
            'Unsupported colorspace [%s]' % colorspace)

    # default settings
    methods_params = _update_params(methods_params)

    # create extra channels
    channels = []

    # Create a set of gabor kernels and apply them
    if 'gabor' in methods:
        for i, frequency in enumerate(methods_params['frequencies']):
            response = []
            for theta in methods_params['thetas']:
                real, imag = skimage.filter.gabor_filter(
                    gray,
                    frequency=frequency,
                    #sigma_x=sigma,
                    #sigma_y=sigma,
                    theta=theta)
                response.append(np.sqrt(real ** 2 + imag ** 2))

            response = np.array(response).max(axis=0)

            channels.append(response)

    # Create relative greyishness
    if 'gaussian' in methods:
        for i, sigma1 in enumerate(methods_params['sigmas']):
            # blur
            response1 = skimage.filter.gaussian_filter(gray, sigma1)
            # blur on a higher level
            response2 = skimage.filter.gaussian_filter(gray, sigma1+1)
            # create relative darkness
            response = response2 - response1

            channels.append(response)

    # Create sobel filter channel
    if 'sobel' in methods:
        channels.append(skimage.filter.sobel(gray))

    # Combine all channels
    allchannels = np.concatenate([
        # greyscale
        np.uint8(gray)[..., np.newaxis],
        # color
        img
    ] + [
        # other channels
        channel[..., np.newaxis]
        for channel
        in channels
    ], -1)

    return allchannels

def get_channel_bounds(methods=['gabor', 'gaussian', 'sobel'],
                       methods_params=None):
    '''Get theoretical bounds of channel values

    Parameters
    ----------
    methods : list, optional
        List of strings indicating channels to be added
    methods_params : dict, optional
        Dictionairy with named options for channel functions

    Returns
    -------
    list
        List of dicts with keys *min* and *max* indicating the
        theoretical boundaries of the channel values
    '''

    # default settings
    methods_params = _update_params(methods_params)

    # initialize all bounds to 0 and 255
    stats = [{'max': 0., 'min': 255.}
             for i in range(get_number_channels(methods, methods_params))]

    # update gabor channel bounds, if requested
    if 'gabor' in methods:
        for i, frequency in enumerate(methods_params['frequencies']):
            k = skimage.filter.gabor_kernel(frequency=frequency, theta=0)
            resp = np.zeros(k.shape) + 255.
            resp[np.real(k) < 0] = 0.
            resp_real = np.sum(resp*np.real(k))
            resp_imag = np.sum(resp*np.imag(k))
            resp = np.sqrt(resp_real**2 + resp_imag**2)
            stats[i]['max'] = resp.max()

    return stats

def get_number_channels(methods=['gabor', 'gaussian', 'sobel'],
                        methods_params=None):
    '''Get number of artificial channels

    Parameters
    ----------
    methods : list, optional
        List of strings indicating channels to be added
    methods_params : dict, optional
        Dictionairy with named options for channel functions

    Returns
    -------
    int
        Number of channels added when using the specified settings
    '''

    methods_params = _update_params(methods_params)

    n = 0
    if 'gabor' in methods:
        n += len(methods_params['frequencies'])

    if 'gaussian' in methods:
        n += len(methods_params['sigmas'])

    if 'sobel' in methods:
        n += 1

    return n

def normalize_channel(channel, channelstats):
    '''Scale channel to uint8 based on maximum possible filter response

    Parameters
    ----------
    channel : np.ndarray
        Array with channel values
    channelstats : dict
        Dictionary with fields *min* and *max* indicating the channel
        value bounds of the dataset and used for normalization

    Returns
    -------
    np.ndarray
        Array with normalized channel values
    '''

    return np.uint8((channel-channelstats['min']) /
                    (channelstats['max']-channelstats['min'])*255)

def _update_params(params):
    '''Set channel options to module defaults'''

    methods_params = {'frequencies':_FREQS,
                      'sigmas':_SIGMAS,
                      'thetas':_THETAS}

    methods_params.update(params)

    return methods_params


#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

import os
from sqlalchemy import Column, String, Integer, create_engine
from flask import Flask, render_template, request, Response, flash, redirect, url_for, jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from flask_moment import Moment
from sqlalchemy.orm import backref
import psycopg2
import json

'''
setup_db(app)
    binds a flask application and a SQLAlchemy service
'''
#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

database_name = "capstone"
database_path = os.environ['DATABASE_URL']
conn = psycopg2.connect(database_path, sslmode='require')

#database_name = "capstone"
# database_path = "postgres://{}:{}@{}/{}".format(
#    'postgres', '123', 'localhost:5432', database_name)

db = SQLAlchemy()

def setup_db(app, database_path=database_path):
    app.config["SQLALCHEMY_DATABASE_URI"] = database_path
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.app = app
    db.init_app(app)
    db.create_all()

'''
CREATE MODELS
MOVIES, ACTORS, POSTER
'''

#----------------------------------------------------------------------------#
# Models.
#----------------------------------------------------------------------------#

class Movie(db.Model):
    __tablename__ = 'movie'

    id = Column(Integer, primary_key=True)
    title = Column(String, nullable=False)
    release_data = Column(String, nullable=False)
    actors = db.relationship('Actor', secondary='poster',
                             backref='movie', lazy=True)

    def __init__(self, title, release_data):
        self.title = title
        self.release_data = release_data

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def format(self):
        return {
            'id': self.id,
            'title': self.title,
            'release_data': self.release_data,
            'actors': [actor.name for actor in self.actors]
        }

class Actor(db.Model):
    __tablename__ = 'actor'

    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False)
    age = Column(String)
    gendar = Column(String)
    movies = db.relationship('Movie', secondary='poster',
                             backref='actor', lazy=True)

    def __init__(self, name, age, gendar):
        self.name = name
        self.age = age
        self.gendar = gendar

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def format(self):
        return {
            'id': self.id,
            'name': self.name,
            'age': self.age,
            'gendar': self.gendar,
            'movies': [movie.title for movie in self.movies]
        }

class Poster(db.Model):
    __tablename__ = 'poster'

    poster_id = Column(Integer, primary_key=True)
    movie_id = Column(Integer, db.ForeignKey(
        'movie.id', ondelete='CASCADE'), primary_key=True)
    actor_id = Column(Integer, db.ForeignKey(
        'actor.id', ondelete='CASCADE'), primary_key=True)

    def insert(self):
        db.session.add(self)
        db.session.commit()

    def update(self):
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()


#!/usr/bin/python

import threading
from time import sleep

class Countdown(threading.Thread):
    def __init__(self, seconds, event):
        self.runTime = seconds
        self.event = event
        self.thread = threading.Thread(target=self.run)
    def run(self):
        if not self.event.isSet():
            self.event.set()
            sleep(self.runTime)
            self.event.clear()


def longestIncreasingPath(matrix):
    if len(matrix) == 0:
        return 0
    rows = len(matrix)
    columns = len(matrix[0])
    dp = [[0 for i in range(columns)] for j in range(rows)]
    def dfs(matrix, i, j, rows, columns, dp):
        if dp[i][j] != 0:
            return dp[i][j]
        maxPath = 0
        if i > 0 and matrix[i - 1][j] > matrix[i][j]:
            maxPath = max(maxPath, dfs(matrix, i - 1, j, rows, columns, dp))
        if i < rows - 1 and matrix[i + 1][j] > matrix[i][j]:
            maxPath = max(maxPath, dfs(matrix, i + 1, j, rows, columns, dp))
        if j > 0 and matrix[i][j - 1] > matrix[i][j]:
            maxPath = max(maxPath, dfs(matrix, i, j - 1, rows, columns, dp))
        if j < columns - 1 and matrix[i][j + 1] > matrix[i][j]:
            maxPath = max(maxPath, dfs(matrix, i, j + 1, rows, columns, dp))
        dp[i][j] = maxPath + 1
        return dp[i][j]
    for i in range(rows):
        for j in range(columns):
            dp[i][j] = dfs(matrix, i, j, rows, columns, dp)
    maxPath = 0
    for i in range(rows):
        for j in range(columns):
            maxPath = max(maxPath, dp[i][j])
    return maxPath

if __name__ == '__main__':
    longestIncreasingPath()


# from container_files import entry

# from infertaces import adapters_azureml

from  interfaces.adapters_azureml import AzureMLPlatform
import os

default_test_experiment = 'Testing'
default_test_environment = 'test-env'
default_training_file = 'hello_there.py'

def test_azureml_connect(test_environment=default_test_environment, test_experiment=default_test_experiment):
    """
        Default experiment = 'Testing'
        Default environment = 'test-env'
    """
    az_plat = AzureMLPlatform(experiment_name=test_experiment, environment_name=test_environment)
    assert az_plat != None
    print("test_azureml_connect(): Connected")
    # print("Experiment: " + az_plat.experiment.name)
    # print("Environment: " + az_plat.environment.name)

def test_azureml_run_training(test_environment=default_test_environment, test_experiment=default_test_experiment):
    """
        runs default_training_file in the specified experiment and environment
    """
    create_training_file()
    az_plat = AzureMLPlatform(experiment_name=test_experiment, environment_name=test_environment)
    print("test_azureml_run_training(): Connected")
    az_plat.run_training(filelist=[default_training_file],  comp_target='local', entrypoint=default_training_file)
    print("test_azureml_run_training(): Complete")
    remove_training_file()

def create_training_file():
    """"
    Creates default_training_file
    """
    with open(default_training_file, 'w') as f:
        f.write("from pip import _internal\n")
        f.write("_internal.main(['list'])\n")
        f.write("print(\"Hello There\")\n")

def remove_training_file():
    """
    deletes default_training_file
    """
    os.remove(default_training_file)


## Condicionales -if-

Numero = float(input("Escribe un número entero: "))
Residuo = Numero%2
if (Residuo == 0):
    print("El número que ingresaste es par")
else:
    print("El número que ingresaste no es par")

Num1 = int(input("Ingrese el primer número entero: "))
Num2 = int(input("Ingrese el segundo número entero: "))

Res1 = Num1 % 2
Res2 = Num2 % 2

if (Res1 == 0 and Res2 == 0):
    print("El primer y segundo número son pares")
elif (Res1 == 0 and Res2 != 0):
    print("El primer número es par y el segundo no es par")
elif (Res1 != 0 and Res2 == 0):
    print("El primer número no es par y el segundo número es par")
else:
    ("El primer y segundo número no son pares")

# Ejercicio 9: Ingresar dos números por consola y verificar
# 1) que los dos números sean mayores a 5
# 2) que el primero sea mayor a 5 y el segundo no
# 3) que el primero no sea mayor a 5 y el segundo si
# 4) que ninguno de los dos sea mayor a 5

# Ejercicio 10: Ingresar una frase por consola
# 1) Verificar si el tamaño del texto es superior a 10 caracteres
# 2) Verificar si la primera letra de la frase es una "A"

Frase = input("Ingrese un texto: ")

if (len(Frase) > 10):
    print("Mayor a 10")
else:
    print("Menor o igual a 10")

PrimerDigito = Frase[0]

if (PrimerDigito == "A"):
    print("La primera letra de la frase es una A")
else:
    print("La primera letra no es una A")


import datetime

"""Unenciphered Enigma message preamble
"""

#Call signs of the statins involved. First the sending station, then the destination(s)
#e.g. 'From P7J to SF9 and 5KQ'
CALL_SIGNS = 'Not yet implemented'

#Date and Time of the origin of the message
DATE_OF_ORIGIN = datetime.datetime.now().date()
TIME_OF_ORIGIN = datetime.datetime.now().time()

NUMBER_OF_LETTERS = 0

# An indication of whether the message is complete,
# or part of a larger message e.g. 'Part 2 of a 4 part message'
SINGLE_OR_MULTIPART = 'Not yet implemented'

# A three letter group to distinguish between different
# types of Enigma traffic
DISCRIMINANT = 'ABC'

# A three letter group, relating to the encoding of the message
INDICATOR_SETTING = 'DEF'

def get_preamble():
    return \
        'Call signs: ' + str(CALL_SIGNS) + '\r\n' + \
        'Date of origin: ' + str(DATE_OF_ORIGIN) + '\r\n' + \
        'Time of origin: ' + str(TIME_OF_ORIGIN) + '\r\n' + \
        'Number of letters: ' + str(NUMBER_OF_LETTERS) + '\r\n' + \
        'Single or multi-part: ' + str(SINGLE_OR_MULTIPART) + '\r\n' + \
        'Discriminant: ' + str(DISCRIMINANT) + '\r\n' + \
        'Indicator setting: ' + str(INDICATOR_SETTING) + '\r\n'


#coding:utf-8
import datetime

from django.shortcuts import Http404

from exchcard.models_main import AvatarPhoto, CardPhoto, Card, Profile
from exchcard_backend_api.permissions import IsOwnerOrReadOnly
from exchcard_backend_api.serializers import AvatarPhotoSerializer, CreateAvatarPhotoSerializer, CardPhotoSerializer
from rest_framework import permissions
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, parser_classes
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework.views import APIView
from utils import utils

#
## post and get files from sae storage
@api_view(['GET',])
@permission_classes([permissions.AllowAny, ])
def sae_s3_storage(request, format=None):
    if request.method == "GET":
        bucket = utils.get_sae_bucket()
        bucket.put_object('1.txt', str(datetime.datetime.now().today()))
        strs1 = str(bucket.generate_url("1.txt"))
        strs2 = str(bucket.get_object_contents('1.txt'))
        data = "%s, %s" %(strs1, strs2)

        return Response({'content':data},
                        status=status.HTTP_200_OK)

@api_view(["POST"])
@permission_classes([permissions.IsAuthenticated, ])
@parser_classes([MultiPartParser, FormParser])
def upload_avatarphoto_by_profile_id(request, pk, format=None):
    """
    主要在settting中设置storage
    :param request:
    :param pk:
    :param format:
    :return:
    """
    if request.method == "POST":
        try:
            profile_from_request = Profile.objects.get(profileuser=request.user)
            if int(pk) == int(profile_from_request.id):
                profile = Profile.objects.get(pk=int(pk))
                photo = AvatarPhoto(owner=profile, avatar=request.data['avatar'])
                photo.save()

                name = photo.avatar.name
                url = photo.avatar.url

                serializer = AvatarPhotoSerializer(photo, context={'request': request})
                data = serializer.data
                data["name"] = name
                data["url"] = url

                return Response(data, status=status.HTTP_201_CREATED)
            else:
                return Response({"details": "request user != user from url",
                                 "id1": pk,
                                 "id2:": profile_from_request.id },
                                 status=status.HTTP_403_FORBIDDEN)

        except Profile.DoesNotExist:
            return Response({"details": "profile of logged user does not exist"},
                          status=status.HTTP_404_NOT_FOUND)

@api_view(["POST"])
@permission_classes([permissions.IsAuthenticated, ])
@parser_classes([MultiPartParser, FormParser])
def upload_avatarphoto(request):
    if request.method == "POST":
        try:
            profile = Profile.objects.get(profileuser=request.user)

            # DJANGO REST, parse request.body
            # print request.data

            # DJANGO
            # print request.FILES
            # print request.POST

            ## 前端按照有表单Form, 文件在request.FILES里面, 也在request.data里面

            # 上传的文件
            f = request.FILES['avatar']
            # 改变文件名，注意不要改变文件格式后缀
            f.name = utils.hash_file_name(f.name)

            photo = AvatarPhoto(owner=profile, avatar=f)
            photo.save()

            serializer = AvatarPhotoSerializer(photo, context={'request': request})
            data = serializer.data

            data["avatarHasBaseUrl"] = 1

            return Response(data=data, status=status.HTTP_201_CREATED)

        except Profile.DoesNotExist:
            return Response({"details":"Internal server error! Can not find Profile object."},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AvatarUploadView(APIView):
    parser_classes = ([MultiPartParser, FormParser]) ## only key is file
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, )

    def post(self, request, pk, format=None):

        try:
            profile_from_request = Profile.objects.get(profileuser=request.user)
            if int(pk) == profile_from_request.id:
                profile = Profile.objects.get(pk=int(pk))
                photo = AvatarPhoto(owner=profile, avatar=request.data['avatar'])
                photo.save()

                name = photo.avatar.name
                url = photo.avatar.url

                aserializer = AvatarPhotoSerializer(photo, context={'request': request})
                data = aserializer.data
                data["name"] = name
                data["avatar_url"] = url

                return Response(data, status=status.HTTP_201_CREATED)

            else:
                return Response({"details": "request user != profileuser",
                             "id1":pk,
                            "id2:":profile_from_request.id },
                            status=status.HTTP_403_FORBIDDEN)
        except Profile.DoesNotExist:
            return Response({"details":"exchcard_backend_api id %s does not exist" % pk},
                            status=status.HTTP_404_NOT_FOUND)

class AvatarPhotoList(APIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
    parser_classes = (MultiPartParser,)

    def get(self, request, format=None):
        photo = AvatarPhoto.objects.all()
        serializer = AvatarPhotoSerializer(photo, many=True , context={'request': request})
        return Response(data=serializer.data, status=status.HTTP_200_OK)

    def post(self, request, format=None):
        profile = Profile.objects.get(profileuser=request.user)
        serializer = CreateAvatarPhotoSerializer(avatar=request.data['avatar'],
                                                 owner=profile,
                                                 context={'request': request})
        if serializer.is_valid():
           serializer.save() # 会保存并返回得到一个object

           return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def pre_save(self, obj):
        obj.owner = Profile.objects.get(profileuser=self.request.user)

### get, update, destory
class AvatarPhotoDetail(APIView):
    parser_classes = (MultiPartParser,)
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)

    def get_object(self, pk):
        try:
            return AvatarPhoto.objects.get(pk=pk)
        except AvatarPhoto.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        photo = self.get_object(pk)
        serializer = AvatarPhoto(photo)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        photo = self.get_object(pk)
        serializer = AvatarPhotoSerializer(photo, data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        photo = self.get_object(pk)
        photo.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

    def pre_save(self, obj):
        obj.owner = Profile.objects.get(profileuser=self.request.user)


#!/usr/bin/env python
#Hennie Veldthuis

import sys
import xml.etree.ElementTree as ET

def main(argv):
    if len(argv) == 3:
        tree = ET.parse(argv[1])
        root = tree.getroot()

        for point in root:
            f0_start  = float(point[13].text)
            f0_end    = float(point[12].text)
            bottom_hz = float(point[5].text)
            top_hz    = float(point[7].text)
            if not((f0_start > bottom_hz) and (f0_start < top_hz) and (f0_end > bottom_hz) and (f0_end < top_hz)):
                # values are incorrect,
                # remove item
                root.remove(point)

        tree.write(argv[2])
    else:
        print("ERROR, not enough arguments, use: python3 spontal_test.py spontal.xml spontal_filtered.xml")

if __name__ == '__main__':
    main(sys.argv)


import json
import math
import os
import time
from concurrent.futures import ThreadPoolExecutor
from urllib import parse

import requests
from rich import print
from rich.console import Console
from rich.progress import Progress
from rich.progress import track
from selenium import webdriver

console = Console()

class qqzone_upload(object):
    def __init__(self, path):
        self.path = path

    def _login_and_wait(self):
        opt = webdriver.ChromeOptions()

        self.driver = webdriver.Chrome(chrome_options=opt)
        self.driver.get("https://i.qq.com")

        while True:
            url = self.driver.current_url
            if "user.qzone.qq.com" in url:
                time.sleep(0.2)
                self.my_uin = str(url[url.rfind("/") + 1 :])
                self.cookies = self.driver.get_cookies()
                self.g_tk = str(
                    self.driver.execute_script("return QZONE.FP.getACSRFToken()")
                )
                break
            else:
                time.sleep(1)

    def _init_session(self):
        self.session = requests.Session()
        for cookie in self.cookies:
            self.session.cookies.set(cookie["name"], cookie["value"])
        self.session.headers = {
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
        }

    def _add_ablum_and_get_id(self):
        ablum_name = self.path[self.path.rfind("\\") + 1 :]
        print(ablum_name)
        url = (
            "https://user.qzone.qq.com/proxy/domain/photo.qzone.qq.com/cgi-bin/common/cgi_add_album_v2?g_tk="
            + self.g_tk
        )
        data = (
            "inCharset=utf-8&outCharset=utf-8&hostUin="
            + self.my_uin
            + "&notice=0&callbackFun=_Callback&format=fs&plat=qzone&source=qzone&appid=4&uin="
            + self.my_uin
            + "&album_type=&birth_time=&degree_type=0&enroll_time=&albumname="
            + parse.quote(ablum_name.encode("utf-8"))
            + "&albumdesc=&albumclass=100&priv=3&queFstion=&answer=&whiteList=&bitmap=10000000&qzreferrer=https%3A%2F%2Fuser.qzone.qq.com%2F201001948%2F4"
        )
        r = self.session.post(url, data, verify=False)
        self.id = (r.text[r.text.find('"id" : ') + 8 :])[
            : (r.text[r.text.find('"id" : ') + 8 :]).find('",')
        ]
        print(self.id)

    def _add_the_photo(self, photo_name):
        photo_path = self.path + "\\" + photo_name
        self.driver.find_element_by_xpath('//*[@id="container"]/div/a/input').send_keys(
            photo_path
        )

    def _input_all_added(self):
        self.driver.find_element_by_xpath('//input[@_phototype="2"]').click()
        self.driver.find_element_by_xpath(
            '//a[@class="op-btn btn-upload j-btn-start j-uploading-hide"]'
        ).click()
        self.driver.switch_to.default_content()
        self.driver.switch_to.frame("tphoto")
        while True:
            try:
                self.driver.find_element_by_xpath(
                    '//span[contains(text(), "继续上传")]'
                ).click()
            except:
                try:
                    self.driver.find_element_by_xpath('//a[@id="back_upload"]').click()
                    time.sleep(3)
                    self.driver.switch_to.default_content()
                    self.driver.switch_to.frame("photoUploadDialog")
                    break
                except BaseException as e:
                    time.sleep(3)

    def _input_photos(self):
        self.driver.switch_to.frame("photoUploadDialog")
        # str = '//li[@_aid="' + self.id + '"]'
        # self.driver.find_element_by_xpath(str).click()

        """
        num=len(self.name_lists)
        num2=num%500
        num1=num//500

        for i in track(range(num1),"Uploading..."):
            for j in range(i*500,i*500+500,1):
                self._add_the_photo(self.name_lists[j])
            self._input_all_added()

        if num2!=0:
            for i in range(num2):
                self._add_the_photo(self.name_lists[i+num1])
            self._input_all_added()
        """

        for i in track(range(len(self.name_lists) - self.start_num), "Uploading..."):
            self._add_the_photo(self.name_lists[i + self.start_num])
            if (i + 1) % 500 == 0 or (i + 1 + self.start_num) >= len(self.name_lists):
                self._input_all_added()

    def _make_name_list(self):
        g = os.walk(self.path)
        for path, dir_list, file_list in g:
            self.name_lists = file_list
            # print(file_list)

    def start_at(self, num=0, make_ablum=False):
        self.start_num = num
        self._make_name_list()
        self._login_and_wait()
        if make_ablum or num == 0:
            self._init_session()
            self._add_ablum_and_get_id()
        wait = input("wait")
        self._input_photos()
        self.driver.quit()


#! /usr/bin/env python
# -*- coding: utf-8 -*-

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        first_occ = 0
        nums_l = len(nums)
        count = 0
        while first_occ < nums_l:
            # The last single number occurence only once.
            if first_occ == nums_l - 1:
                nums[count] = nums[first_occ]
                count += 1
                break

            # Always keep the first occurence of a number
            first_num = nums[first_occ]
            second_num = nums[first_occ+1]
            # Move the number occurence only once to it's position
            if first_num != second_num:
                nums[count] = first_num
                count += 1
                first_occ += 1
                continue

            # Move the number occur twice to their positions
            if first_num == second_num:
                nums[count] = first_num
                nums[count+1] = second_num
                next_occ = first_occ+2
                while next_occ < nums_l and nums[next_occ] == second_num:
                    next_occ += 1
                count += 2
                first_occ = next_occ
        return count

"""
[]
[1,1,1,1,2,2,2,3,3,3,4,5,6,6,6,7]
"""


# Read a list of integers:
# a = [int(s) for s in input().split()]
# Print a value:
# print(a)
N, K = tuple([int(s) for s in input().split()])
Q = ["I"]*N
#print(Q)
for i in range(K):
  start, stop = tuple([int(s) for s in input().split()])
  Q[start-1:stop] = ["."]*(stop-start+1)
  #print(Q)

print("".join(Q))

data/7.D. Lists: Bowling/submissions/Mathieu BEN/main.py


# 167. Two Sum II - Input Array Is Sorted (Easy)
# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
# https://www.youtube.com/watch?v=sAQT4ZrUfWo&list=PLU_sdQYzUj2keVENTP0a5rdykRSgg9Wp-&index=5

class Solution: # O(N) time, O(1) space
    def twoSum(self, numbers, target):
        pointer1 = 0
        pointer2 = len(numbers)-1

        while pointer1 < pointer2: # O(N) time, O(1) space
            curr_sum = numbers[pointer1] + numbers[pointer2]
            if curr_sum < target:
                pointer1 += 1
            elif curr_sum > target:
                pointer2 -= 1
            else:
                return [pointer1+1, pointer2+1]

if __name__ == "__main__":
    solution = Solution()
    # testcase 1
    numbers = [2,7,11,15]
    target = 9
    output = solution.twoSum(numbers, target)
    print(output)


from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QHBoxLayout, QLabel, QBoxLayout, QVBoxLayout, QPushButton, QWidget, QInputDialog
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from GameController.GameControllerModel import GameControllerModel

class QDungeonSelector(QWidget):
    def __init__(self, parent: QWidget, model: GameControllerModel):
        super(QWidget, self).__init__()
        self.model = model
        self.lblCurrentDungeon = QLabel()
        self.layoutMainHor = QHBoxLayout()
        self.currentChapter = 1
        self.requested_w, self.requested_h = parent.get_toolbar_size()
        self.initUI()

    def initUI(self):
        # Init currentDungeonWidget
        self.lblCurrentDungeon.setText("")
        self.lblCurrentDungeon.setStyleSheet("background-color: (225,225,225)")
        self.lblCurrentDungeon.setAlignment(Qt.AlignCenter)
        self.lblCurrentDungeon.setFixedWidth(self.requested_w - 10)
        self.lblCurrentDungeon.setFixedHeight(self.requested_h - 10)
        self.changeCurrentChapter(1)
        self.lblCurrentDungeon.mousePressEvent = self.onChapterClick
        self.layoutMainHor.addWidget(self.lblCurrentDungeon)
        self.layoutMainHor.setSpacing(0)
        self.layoutMainHor.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layoutMainHor)
        self.SelectionEnabled = False

    def onChapterClick(self, event):
        if self.SelectionEnabled:
            self.askForChapter()

    def askForChapter(self):
        chapters = self.model.getChapters()
        item, ok = QInputDialog.getItem(self, "Select chapter",
                                        "Chapter:", chapters, self.currentChapter - 1, False)
        if ok and item:
            selected_ch = self.model.getChNumberFromString(item)
            if selected_ch != -1:
                self.changeCurrentChapter(selected_ch)

    def changeCurrentChapter(self, ch_number: int):
        self.lblCurrentDungeon.clear()
        pixmap = QtGui.QPixmap(self.model.getChapterImagePath(ch_number))
        pixmap = pixmap.scaled(self.lblCurrentDungeon.width(), self.lblCurrentDungeon.height(), Qt.KeepAspectRatio)
        self.lblCurrentDungeon.setPixmap(pixmap)
        self.currentChapter = ch_number


# -*- coding: utf-8 -*-
"""
Created on Mon Jan 25 13:53:07 2021

@author: m-lin
"""

# ライブラリの読み込み
import pandas as pd
from sklearn.metrics import accuracy_score

# データの読み込み
train = pd.read_csv('train.tsv', sep='\t')

# データの確認
print(train.head())

# 'id'の削除と確認
train = train.drop(train.columns[[0]], axis=1)
print(train.head())
print(train.shape)

print(train.iloc[0,0])

# trainデータのclassを予測
y_train_preds = []

for i in range(len(train)):
    l_wd = train.iloc[i,1] * train.iloc[i,2] # left_weight * left_distance
    r_wd = train.iloc[i,3] * train.iloc[i,4] # right_weight * right_distance

    if l_wd > r_wd:
        y_train_preds.append(0)

    elif l_wd == r_wd:
        y_train_preds.append(1)

    elif l_wd < r_wd:
        y_train_preds.append(2)

# trainデータのclass（目的変数）を取得
y_train_true = train['class']

# accuracyを計算する
score = accuracy_score(y_train_true, y_train_preds)
print(score)


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

Created on Wed Sep 30 21:44:07 2020

Modern Art Monte Carlo Simulation
    a. playing field is 800 wide and 500 high. origin is top left.
    b. get user input on total throws. validate positive
    b. generate random point
    c. if in red, if yellow, if green, if blue, if green and blue, if black or miss
    d. count results, format, display
"""
# imports
import math
import random
import time

# initialize/assign vars
start = time.perf_counter()
total_throws = 0
red = 0
green = 0
blue = 0
grey = 0
black = 0
yellow = 0
misses = 0

def in_circle(x1, y1, x2, y2, radius):
    """in_circle func for repeated use with green, blue, grey, black"""
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2) < radius

def distance(x1, y1, x2, y2):
    """distance func for use with black circle"""
    return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)

# red area point range
redx = [50, 100]
redy = [50, 450]

# yellow area (split into 3) point ranges
y1x = [600, 650]
y1y = [50, 400]
y2x = [650, 750]
y2y = [50, 100]
y3x = [700, 750]
y3y = [100, 400]

# grey is in green and blue, elif green, elif blue
# green area. center is (300,150), radius is 100
# blue area. center is (450,150), radius of circle is 100
# if dist of rand(x,y) to center(x,y) < radius, then in circle
green_x = 300
green_y = 150
green_radius = 100
blue_x = 450
blue_y = 150
blue_radius = 100

# black center is (375,375), full radius is 75, white  radius is 25
# if dist rand(x,y) to white center < black radius
# if dist greater than 25:
# then black +=1
black_x = 375
black_y = 375
black_radius = 75
white_radius = 25

# get input on number of throws
while True:
    total_throws = int(input('Number of throws: '))
    if total_throws > 0:
        break
    else:
        print('Invalid, try again!', end='')
        continue

# for loop (known # of iterations), generate random(x,y), determine hit/miss
for num in range(1, total_throws + 1):
    pointx = random.uniform(0, 800)
    pointy = random.uniform(0, 500)

    if (pointx >= redx[0] and pointx <= redx[1]) and (pointy >= redy[0] and pointy <= redy[1]):
        red += 1

    elif (pointx >= y1x[0] and pointx <= y1x[1]) and (pointy >= y1y[0] and pointy <= y1y[1]):
        yellow += 1

    elif (pointx >= y2x[0] and pointx <= y2x[1]) and (pointy >= y2y[0] and pointy <= y2y[1]):
        yellow += 1

    elif (pointx >= y3x[0] and pointx <= y3x[1]) and (pointy >= y3y[0] and pointy <= y3y[1]):
        yellow += 1

    elif in_circle(pointx, pointy, green_x, green_y, green_radius) and in_circle(pointx, pointy, blue_x, blue_y, blue_radius):
        grey += 1

    elif in_circle(pointx, pointy, green_x, green_y, green_radius):
        green += 1

    elif in_circle(pointx, pointy, blue_x, blue_y, blue_radius):
        blue += 1

    elif in_circle(pointx, pointy, black_x, black_y, black_radius):

        if distance(pointx, pointy, black_x, black_y) > 25:
            black += 1

    else:
        misses += 1

end = time.perf_counter()
print('Total time elapsed: {:.2f} seconds'.format(end - start), end='\n' * 2)

# format results and display
colors = ['Red:', 'Green:', 'Blue:', 'Grey:', 'Black:', 'Yellow:', 'Misses:']
results = [red, green, blue, grey, black, yellow, misses]
percent_results = [format(x / total_throws, '.2%') for x in results]
for x, y, z in zip(colors, results, percent_results):
    print('{:<15}'.format(x), '{:>10,}'.format(y), '({})'.format(z))


from django.conf.urls import url

from ..views import JudgeServerHeartbeatAPI, LanguagesAPI, WebsiteConfigAPI, SoftwaresAPI, SlideshowsAPI

urlpatterns = [
    url(r"^website/?$", WebsiteConfigAPI.as_view(), name="website_info_api"),
    url(r"^softwares/?$", SoftwaresAPI.as_view(), name="softwares_api"),
    url(r"^slideshows/?$", SlideshowsAPI.as_view(), name="slideshows_api"),
    url(r"^judge_server_heartbeat/?$", JudgeServerHeartbeatAPI.as_view(), name="judge_server_heartbeat_api"),
    url(r"^languages/?$", LanguagesAPI.as_view(), name="language_list_api")
]