import time
import stair_world.stair_world
import gymnasium
import numpy as np
from stable_baselines3.common.env_checker import check_env
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3 import DQN, A2C
from gymnasium.wrappers import NormalizeReward
import imageio

env = gymnasium.make("StairWorld-v0", render_mode="rgb_array")
env = NormalizeReward(env)
print(env.reset(seed=22))
model = A2C('MultiInputPolicy', env, verbose=1).learn(total_timesteps=1e6)
mean_reward, std_reward = evaluate_policy(model, model.get_env(), n_eval_episodes=10)
print(f'The mean reward was {mean_reward} and the standard deviation was {std_reward}.')
#check_env(env, skip_render_check=False)

model.save("a2c_stair")
del model

model = A2C.load("a2c_stair")

images = []
obs, _info = env.reset()
img = env.render()
images.append(img)
print(obs)
for i in range(1000):
    action, _states = model.predict(obs)
    obs, reward, terminated, info, done = env.step(action)
    print(obs, action)
    img = env.render()
    images.append(img)
    # env.render()
    time.sleep(1)

    if terminated:
        break
imageio.mimsave("stair_game.gif", [np.array(img) for i, img in enumerate(images)], fps=2)


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import nltk
import codecs

# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')

file = 'train-2.csv'
data = pd.read_csv(file)

#print data.head(20)
negative = data.loc[data['is_duplicate'] == 0]
duplicate = data.loc[data['is_duplicate'] == 1]

q1 = data['question1'].values
q2 = data['question2'].values

q1t, q2t = [], []
#print type(q1[301412])
#print q1[301412].split()
#print nltk.wordpunct_tokenize(q1[301412])

for q in q1:
	if (type(q) != float):
		q = q.lower()
		q_tmp = nltk.wordpunct_tokenize(q)
		q1t.append(q_tmp)

for q in q2:
	if (type(q) != float):
		q = q.lower()
		q_tmp = nltk.wordpunct_tokenize(q)
		q2t.append(q_tmp)

#print data.head(20)

#print 'Negative:', negative.shape
#print 'Duplicate:', duplicate.shape

#Dataset is slightly unbalanced


#-*- coding:utf-8 -*-
# author:ekihin
# datetime:2020-04-07 22:12
# software: PyCharm
import socket

sk = socket.socket()

ip = ('127.0.0.1',13000)
sk.connect(ip)

send_data = input(">>>")
sk.sendall(send_data.encode("utf-8"))

server_data = sk.recv(1024).decode("utf-8")
print("服务端：",server_data)

sk.close()


from django.db import models

from ara.db.models import MetaDataModel

class Attachment(MetaDataModel):
    class Meta(MetaDataModel.Meta):
        verbose_name = "첨부파일"
        verbose_name_plural = "첨부파일 목록"

    file = models.FileField(
        upload_to="files",
        verbose_name="링크",
        max_length=200,
    )

    size = models.BigIntegerField(
        default=-1,
        verbose_name="용량",
    )

    mimetype = models.CharField(
        default="text/plain",
        max_length=128,
        verbose_name="타입",
    )

    def __str__(self) -> str:
        return self.file.name


import os
from io import BytesIO
from socket import socket, AF_INET, SOCK_STREAM
from typing import Callable
from PIL import Image
from config import spectrogram_filter, spectrogram_queue, slice_genre_aggregator
from config.constants import SLICE_EDGE, SLICES_NUMBER_BYTES
from config.genre_computer_request_manager import REQUEST_ID_BYTES_NUMBER
from src.business.abstract_classes.AbstractSyncReceivePipelineStage import AbstractSyncReceivePipelineStage
from src.helpers.HighLevelSocketWrapper import HighLevelSocketWrapper

class SpectrogramFilter(AbstractSyncReceivePipelineStage):
    def __init__(self, name: str = 'SpectrogramFilter', log_func: Callable[[str], None] = print):
        super().__init__(name, log_func)
        self.__server_socket = HighLevelSocketWrapper(socket(AF_INET, SOCK_STREAM))
        self.__server_socket.bind((spectrogram_filter.HOST, spectrogram_filter.PORT))
        self.__server_socket.listen()
        self._log_func(f'[{self._name}] '
                       f'ServerSocket opened on {spectrogram_filter.HOST}:{spectrogram_filter.PORT}!')

    def _receive_message(self) -> bytes:
        client_socket, addr = self.__server_socket.accept()
        self._log_func(f'[{self._name}] Client connected: {addr}!')
        message = client_socket.receive_message()
        client_socket.close()
        return message

    def _process_message(self, message: bytes) -> bytes:
        request_id = message[:REQUEST_ID_BYTES_NUMBER]
        spectrogram = message[REQUEST_ID_BYTES_NUMBER:]
        slices_number = self.__get_slices_number(spectrogram)
        slices_number_bytes = slices_number.to_bytes(SLICES_NUMBER_BYTES, 'big', signed=False)
        self._log_func(f'[{self._name}] Received and processed message:'
                       f'\n\tReceived message length: {len(message)}'
                       f'\n\tRequestID: {request_id}'
                       f'\n\tSpectrogram length: {len(spectrogram)}'
                       f'\n\tSlices number: {slices_number}'
                       f'\n\tSent message to SliceGenreAggregator length: {len(request_id) + len(slices_number_bytes)}'
                       f'\n\tSent message to SpectrogramQueue length: {len(message) + len(slices_number_bytes)}')
        return request_id + slices_number_bytes + spectrogram

    def _send_message(self, message: bytes) -> None:
        client_socket = HighLevelSocketWrapper(socket(AF_INET, SOCK_STREAM))
        client_socket.connect((slice_genre_aggregator.HOST, slice_genre_aggregator.SLICE_NUMBER_PORT))
        client_socket.send_message(message[:REQUEST_ID_BYTES_NUMBER + SLICES_NUMBER_BYTES])
        client_socket.close()

        client_socket = HighLevelSocketWrapper(socket(AF_INET, SOCK_STREAM))
        client_socket.connect((spectrogram_queue.HOST, spectrogram_queue.PUT_PORT))
        client_socket.send_message(message)
        client_socket.close()

    @staticmethod
    def __get_slices_number(spectrogram: bytes) -> int:
        spectrogram = BytesIO(spectrogram)
        spectrogram = Image.open(spectrogram)
        return spectrogram.width // SLICE_EDGE

    def run(self) -> None:
        try:
            AbstractSyncReceivePipelineStage.run(self)
        finally:
            self.__server_socket.close()

class DebugSpectrogramFilter(SpectrogramFilter):
    def __init__(self, output_dir: str, name: str = 'SpectrogramFilter', log_func: Callable[[str], None] = print):
        super().__init__(name, log_func)
        self.__output_dir = output_dir

    def _process_message(self, message: bytes) -> bytes:
        spectrogram = message[REQUEST_ID_BYTES_NUMBER:]
        with open(os.path.join(self.__output_dir, 'SpectrogramFilter - Spectrogram.png'), 'wb') as f:
            f.write(spectrogram)

        message = super()._process_message(message)
        return message

if __name__ == '__main__':
    DebugSpectrogramFilter('../../../debug_files/').run()
    # SpectrogramFilter().run()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Django-Live-Templates is an extension to Django and Channels which adds
support for live updating Django template snippets on model changes.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

__version_info__ = {
    'major': 0,
    'minor': 1,
    'micro': 0,
    'releaselevel': 'alpha',
}

def get_version():
    """
    Return the formatted version information
    """
    vers = ["%(major)i.%(minor)i" % __version_info__, ]

    if __version_info__['micro']:
        vers.append(".%(micro)i" % __version_info__)
    if __version_info__['releaselevel'] != 'final':
        vers.append('%(releaselevel)s' % __version_info__)
    return ''.join(vers)

__version__ = get_version()


import os
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import matplotlib.pyplot as plt
from tensorflow.keras.callbacks import ReduceLROnPlateau

data_path = r'C:\Users\15098\Desktop\cnn_char_train'
character_folders = os.listdir(data_path)
label = 0
LABEL_temp = {}
if(os.path.exists('./train_data.list')):
    os.remove('./train_data.list')
if(os.path.exists('./test_data.list')):
    os.remove('./test_data.list')
for character_folder in character_folders:
    with open('./train_data.list', 'a') as f_train:
        with open('./test_data.list', 'a') as f_test:
            if character_folder == '.DS_Store' or character_folder == '.ipynb_checkpoints' or character_folder == 'data23617':
                continue
            #print(character_folder + " " + str(label))
            LABEL_temp[str(label)] = character_folder     #存储一下标签的对应关系
            character_imgs = os.listdir(os.path.join(data_path, character_folder))
            for i in range(len(character_imgs)):
                if i%10 == 0:
                    f_test.write(os.path.join(os.path.join(data_path, character_folder), character_imgs[i]) + "\t" + str(label) + '\n')
                else:
                    f_train.write(os.path.join(os.path.join(data_path, character_folder), character_imgs[i]) + "\t" + str(label) + '\n')
    label = label + 1
print('图像列表已生成')


import logging
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from fn_mitre_integration.lib import mitre_attack_utils
from resilient_lib import ResultPayload

class FunctionComponent(ResilientComponent):
    """Component that implements Resilient function 'mitre_tactic_information

        This function takes a tactic name or id and returns techniques this
        tactic uses

    """

    def __init__(self, opts):
        """constructor provides access to the configuration options"""
        super(FunctionComponent, self).__init__(opts)
        self.opts = opts
        self.options = opts.get("fn_mitre_integration", {})

    @handler("reload")
    def _reload(self, event, opts):
        """Configuration options have changed, save new values"""
        self.opts = opts
        self.options = opts.get("fn_mitre_integration", {})

    @function("mitre_tactic_information")
    def _mitre_tactic_information_function(self, event, *args, **kwargs):
        """Function: Get information about MITRE tactic"""
        try:
            # Get the function parameters:
            mitre_tactic_id = kwargs.get("mitre_tactic_id")  # text
            mitre_tactic_name = kwargs.get("mitre_tactic_name")  # text

            log = logging.getLogger(__name__)
            log.info("mitre_tactic_id: %s", mitre_tactic_id)
            log.info("mitre_tactic_name: %s", mitre_tactic_name)

            if not mitre_tactic_id and not mitre_tactic_name:
                raise ValueError("Neither name nor id is provided for getting tactic information.")

            result_payload = ResultPayload("fn_mitre_integration", mitre_tactic_id=mitre_tactic_id,
                                           mitre_tactic_name=mitre_tactic_name)
            yield StatusMessage("starting...")
            yield StatusMessage("query MITRE STIX TAXII server, and it can take several minutes....")

            tactics = mitre_attack_utils.get_tactics_and_techniques(tactic_names=mitre_tactic_name,
                                                                    tactic_ids=mitre_tactic_id, opts=self.opts,
                                                                    function_opts=self.options)
            yield StatusMessage("done...")

            results = {
                "mitre_tactics": tactics
            }
            # Produce a FunctionResult with the results
            yield FunctionResult(result_payload.done(True, results))
        except Exception as e:
            log.exception(str(e))
            yield FunctionError()


from openpyxl import load_workbook
from db import process_db
from model.ErrorData import OracleErrorData
import os
cur_dir = os.path.dirname(os.path.realpath(__file__))
excel_path = os.path.join(cur_dir, 'dataset.xlsx')

def save_dataset(kind):
    # 엑셀파일 로드
    # print(excel_path)
    load_wb = load_workbook(excel_path, data_only=True)
    if kind == 'oracle_error':
        oracle_err_sheet = load_wb['oracle_data']

        oracle_err_dataset = []
        for row in oracle_err_sheet.rows:
            oracle_err_data = []
            for cell in row:
                if cell.value is not None:
                    oracle_err_data.append(cell.value[:len(cell.value) - 1])
                else:
                    oracle_err_data.append(cell.value)

            if oracle_err_data[0] is not None and oracle_err_data[0].startswith('ORA'):
                oracle_err_dataset.append(oracle_err_data)

        # DB에 데이터셋 저장
        result = process_db.insert_dataset(kind, oracle_err_dataset)

        return result

def load_dataset(kind):
    if kind == 'oracle_error':
        oracle_err_dataset = process_db.load_dataset(kind)
        oracle_errzip = dict()
        for data in oracle_err_dataset:
            oracle_errzip[data['error_code']] = OracleErrorData(data['error_code'],
                                                                data['situation'],
                                                                data['cause'],
                                                                data['description'],
                                                                data['solution'])

        return oracle_errzip


from aoc.utils import get_input
from itertools import permutations

def solve_part_two(input: str) -> int:
    numbers = list(map(int, input.splitlines()))
    expected_sum = 2020
    combinations = permutations(numbers, 3)

    for a, b, c in combinations:
        if a + b + c == expected_sum:
            return a * b * c

    raise Exception(f'No three numbers add up to {expected_sum}.')

if __name__ == "__main__":
    expense_report = get_input(2020, 1)
    result = solve_part_two(expense_report)
    print(result)


# Script for predicting change in feature based on
# Speed at start

import numpy as np
import matplotlib.pyplot as plt
import mne
import gc
import scipy.stats
from statsmodels.stats.diagnostic import lilliefors
import utils.utils as utils
from mne_bids import BIDSPath, read_raw_bids, print_dir_tree, make_report
from alive_progress import alive_bar
import time
from statannot import add_stat_annotation
import seaborn as sb
from scipy import stats
from scipy.stats import pearsonr, spearmanr
import matplotlib
matplotlib.use('TkAgg')
import warnings
warnings.filterwarnings("ignore")

# Set analysis parameters
feature_name = "peak_speed" # out of ["peak_acc", "mean_speed", "move_dur", "peak_speed", "stim_time", "peak_speed_time", "move_onset_time", "move_offset_time"]
datasets_off = [0, 1, 2, 6, 8, 11, 13, 14, 15, 16, 17, 19, 20, 26, 27]
normalize = True
datasets_on = [3, 4, 5, 7, 9, 10, 12, 18, 21, 22, 23, 24, 25]
datasets_all = np.arange(28)

# Load feature matrix
feature_matrix = np.load(f"../../Data/{feature_name}.npy")
n_datasets, _,_, n_trials = feature_matrix.shape

# Choose only the stimulation period
feature_matrix = feature_matrix[:, :, 0, :]

# Reshape matrix such that blocks from one condition are concatenated
feature_matrix = np.reshape(feature_matrix, (n_datasets, 2, n_trials))

# Delete the first 5 movements
feature_matrix = feature_matrix[:, :, 5:]
feature_matrix_non_norm = feature_matrix.copy()

# Get median speed at beginning of task
median_feature_start = np.nanmedian(feature_matrix[:, :, :5], axis=(1, 2))

# Normalize to average of first 5 movements
if normalize:
   feature_matrix = utils.norm_perc(feature_matrix)
   #feature_matrix = utils.norm_perc_every_t_trials(feature_matrix, 45)

# Plot correlation between initial speed and difference in condition speeds
#datasets_off = datasets_all
#feature_matrix_non_norm = feature_matrix
off_fast_start = np.nanmedian(feature_matrix[datasets_off, 1, :], axis=1) - np.nanmedian(feature_matrix[datasets_off, 0, :], axis=1)
x = off_fast_start
y = median_feature_start[datasets_off]
y = np.percentile(feature_matrix_non_norm[datasets_off, :, :45], 90, axis=(1,2)) \
    - np.percentile(feature_matrix_non_norm[datasets_off, :, :45], 10, axis=(1,2))
y2 = np.percentile(feature_matrix_non_norm[datasets_off, :, -45:], 90, axis=(1,2)) \
    - np.percentile(feature_matrix_non_norm[datasets_off, :, -45:], 10, axis=(1,2))
corr, p = spearmanr(x, y)
plt.figure()
sb.regplot(x=x, y=y)
plt.title(f"Off corr = {np.round(corr, 2)}, p = {np.round(p, 3)}", fontweight='bold')
# Add labels
feature_name_space = feature_name.replace("_", " ")
if normalize:
    plt.xlabel(f"Difference Fast-Slow of change in {feature_name_space} \n in first half of block[%]", fontsize=12)
else:
    plt.xlabel(f"Difference Fast-Slow in {feature_name_space} \n in first half of block[%]", fontsize=12)
plt.ylabel(f"Initial {feature_name_space}", fontsize=12)

# Save figure
plt.subplots_adjust(bottom=0.2, left=0.2)
plt.savefig(f"../../Plots/corr_diff_init_{feature_name}_normalize_{normalize}.svg", format="svg", bbox_inches="tight")

plt.show()

plt.figure()
y = np.percentile(feature_matrix_non_norm[datasets_off, 1, :45], 90, axis=(1)) \
    - np.percentile(feature_matrix_non_norm[datasets_off, 1, :45], 10, axis=(1))
y2 = np.percentile(feature_matrix_non_norm[datasets_off, 1, -45:], 90, axis=(1)) \
    - np.percentile(feature_matrix_non_norm[datasets_off, 1, -45:], 10, axis=(1))
x = np.repeat(["First", "Last"], len(datasets_off))
box = sb.boxplot(x=x, y=np.concatenate((y, y2)), showfliers=False)
sb.stripplot(x=x, y=np.concatenate((y, y2)))


masalar = dict()
for i in range(10):
    masalar[i] = 0

def hesapEkle():
    masaNo = int(input("Masa No: "))
    gec = masalar[masaNo]
    eklenecek = float(input("Eklenecek ücret: "))
    toplam = gec + eklenecek
    masalar[masaNo] = toplam

def hesapSil():
    masaNo = int(input("Masa No: "))
    gec = masalar[masaNo]
    eksilecek = float(input("Eksilecek ücret: "))
    cik = gec - eksilecek
    if cik < 0:
        print("mal")
    else:
        masalar[masaNo] = cik

def hesapKontrol(dosyaadi):
    try:
        dosya = open(dosyaadi)
        veriler = dosya.read()
        veriler = veriler.split("\n")
        veriler.pop()
        flag = True

    except FileNotFoundError:
        dosya = open(dosyaadi, "w")
        dosya.close()
        flag = False
    if flag:
        for i in enumerate(veriler):
            masalar[i[0]] = float(i[1])
    else:
        pass

def kayitGuncelle():
    dosya = open("lokkayıt.txt", "w")
    for i in range(10):
        ucret = masalar[i]
        ucret = str(ucret)
        dosya.write(ucret + "\n")
    dosya.close()

def main():
    hesapKontrol("lokkayıt.txt")
    print("""
    1-Masaları Görüntüle
    2-Hesap Ekle
    3-Hesap Sil
    4-Çıkış

    """)

    secim = input("işlemin:")

    if secim == "1":
        for i in range(10):
            print("Masa {} için hesap: {}".format(i, masalar[i]))
        main()
    elif secim == "2":
        hesapEkle()
        kayitGuncelle()
        main()
    elif secim == "3":
        hesapSil()
        kayitGuncelle()
        main()
    elif secim == "4":
        quit()
    else:
        print("yo")
        main()
main()


from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from restaurant.models import Restaurant
from restaurant.serializers import RestaurantSerializer

from .utils import sample_restaurant

RESTAURANTS_URL = reverse("restaurant:restaurant")

class PublicRestaurantApiTests(TestCase):
    """Test unauthenticated restaurant API access"""

    def setUp(self):
        self.client = APIClient()

    def test_auth_required(self):
        """Test that authentication is required"""
        res = self.client.get(RESTAURANTS_URL)

        self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)

class PrivateRestaurantApiTests(TestCase):
    """Test unauthenticated restaurant API access"""

    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_user("test@gmail.com", "testpass")
        self.client.force_authenticate(self.user)

    def test_create_restaurant(self):
        """Test creating restaurant failed for employees"""
        payload = {"title": "Sultan's Dine"}
        res = self.client.post(RESTAURANTS_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)

class AdminUsersApiTests(TestCase):
    """Test the admin restaurant API"""

    def setUp(self):
        self.client = APIClient()
        self.user = get_user_model().objects.create_superuser(
            "admin@gmail.com", "testpass"
        )
        self.client.force_authenticate(self.user)

    def test_retrieve_restaurants(self):
        """Test retrieving a list of restaurants"""
        sample_restaurant()
        sample_restaurant()

        res = self.client.get(RESTAURANTS_URL)

        restaurants = Restaurant.objects.all().order_by("-id")
        serializer = RestaurantSerializer(restaurants, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(res.data, serializer.data)

    def test_create_restaurant(self):
        """Test creating restaurant for admins"""
        payload = {"title": "Sultan's Dine"}
        res = self.client.post(RESTAURANTS_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_201_CREATED)
        restaurant = Restaurant.objects.get(id=res.data["id"])
        for key in payload.keys():
            self.assertEqual(payload[key], getattr(restaurant, key))


import cStringIO
import time

from google3.pyglib import resources

# Global data
_build_dict = None

def _ParseBuildData(filename):
  """Read build data from external file.

  Uses default values if build data file not available.

  Returns dictionary of build data info
  """

  # Start with empty defaults
  build_data = {
    'BUILDINFO' : '',
    'BUILDLABEL' : '',
    'BUILDTOOL' : '',
    'CHANGELIST' : '-1',
    'CLIENTNAME' : '',
    'CLIENTSTATUS' : '-2',
    'DEPOTPATH' : '',
    'PAROPTIONS' : '',
    'PLATFORM' : '',
    'TARGET' : '',
    'TIMESTAMP' : '',
    }

  # Read generated build info if available
  try:
    build_data_str = resources.GetResource(filename)
    # Parse as key/value pairs
    for line in build_data_str.splitlines():
      # Skip comments, blanks, and syntax errors
      if line.startswith('#') or not line.strip() or ':' not in line:
        continue

      key, value = line.split(':',1)
      build_data[key] = value
  except IOError:
    pass  # Build data not available

  return build_data

def _InitBuildData():
  """Read build data from external file, if not already read."""
  global _build_dict
  if not _build_dict:
    _build_dict = _ParseBuildData('google3/pyglib/build_data.txt')

def BuildInfo():
  """Return user, host, and directory of builder, as string"""
  _InitBuildData()
  return _build_dict.get('BUILDINFO', '')

def BuildLabel():
  """Return build label (passed to make-{opt,dbg} -l) as string"""
  _InitBuildData()
  return _build_dict.get('BUILDLABEL', '')

def BuildTool():
  """Return the build tool as string if we know it"""
  _InitBuildData()
  return _build_dict.get('BUILDTOOL', '')

def Changelist():
  """Return client workspace changelist, as int"""
  _InitBuildData()
  cl = _build_dict.get('CHANGELIST', '')
  try:
    changelist = int(cl.strip())
  except ValueError:
    changelist = -1
  return changelist

def ClientInfo():
  """Return Perforce client changelist and status as descriptive string"""
  _InitBuildData()
  info = ''
  cl = Changelist()
  if cl == -1:
    info = ''
  elif cl == 0:
    info = 'unknown changelist'
  else:
    cs = ClientStatus()
    dp = DepotPath()
    if cs == 1:
      status_info = ' in a mint client based on %s' % dp
    elif cs == 0:
      status_info = ' in a modified client based on %s' % dp
    else:
      status_info = ' possibly in a modified client'
    info = 'changelist %d%s' % (cl, status_info)
  return info

def ClientName():
  """Return Perforce client name, as string"""
  _InitBuildData()
  return _build_dict.get('CLIENTNAME', '')

def ClientStatus():
  """Return Perforce client status, as int"""
  _InitBuildData()
  tmp_str = _build_dict.get('CLIENTSTATUS', '')
  try:
    status = int(tmp_str.strip())
  except ValueError:
    status = -1
  return status

def DepotPath():
  """Return Perforce depot path, as string"""
  _InitBuildData()
  return _build_dict.get('DEPOTPATH', '')

def ParOptions():
  """Return list of autopar options, as string"""
  _InitBuildData()
  return _build_dict.get('PAROPTIONS', '')

def Platform():
  """Return google platform as string"""
  _InitBuildData()
  return _build_dict.get('PLATFORM', '')

def Target():
  """Return build target as string"""
  _InitBuildData()
  return _build_dict.get('TARGET', '')

def Timestamp():
  """Return timestamp in seconds since epoch, as int"""
  _InitBuildData()
  ts = _build_dict.get('TIMESTAMP', '')
  try:
    timestamp = int(ts.strip())
  except ValueError:
    timestamp = -1
  return timestamp

def BuildData():
  """Return all build data as a nicely formatted string."""
  _InitBuildData()
  buf = cStringIO.StringIO()

  timestamp = Timestamp()
  buf.write('Built on %s (%d)\n' %
            (time.asctime(time.localtime(timestamp)), timestamp))

  buf.write('Built by %s\n' % BuildInfo())

  buf.write('Built as %s\n' % Target())

  clientinfo = ClientInfo()
  if clientinfo:
    buf.write('Built from %s\n' % clientinfo)

  buildlabel = BuildLabel()
  if buildlabel:
    buf.write('Build label: %s\n' % buildlabel)

  buf.write('Build platform: %s\n' % Platform())

  buildtool = BuildTool()
  if buildtool:
    buf.write('Build tool: %s\n' % buildtool)

  paropts = ParOptions()
  if paropts:
    buf.write('\nBuilt with par options %s\n' % paropts)

  data_str = buf.getvalue()
  buf.close()

  return data_str


import requests
import json
from keys import my_apikey, my_hash

# Requesting chracters from Marvel API

characters = requests.request(
  "GET",
  "http://gateway.marvel.com/v1/public/characters?ts=1&apikey={api1}&hash={hash1}"
  .format(api1=my_apikey, hash1=my_hash))
charactersJSON = characters.json()

numberOfPages = charactersJSON['data']['total'] / 100
print(numberOfPages)
offset = 0
Master_dict = {}
Master_dict_temp = {}
while numberOfPages > 0:
  people = requests.get(
    "http://gateway.marvel.com/v1/public/characters?ts=1&apikey={api1}&hash={hash1}&limit=100&offset={offset1}"
    .format(api1=my_apikey, hash1=my_hash, offset1=offset))
  peopleJSON = people.json()
  for chracter_id in peopleJSON["data"]["results"]:
    if 'image_not_available' not in str(chracter_id["thumbnail"]["path"]):

      Master_dict_temp[chracter_id['name']] = chracter_id["thumbnail"][
        "path"] + "/portrait_incredible.jpg"

  Master_dict.update(Master_dict_temp)

  offset = offset + 100
  numberOfPages = numberOfPages - 1
  Master_dict_temp = {}


# "Database code" for the DB Forum.

import psycopg2
import bleach

DBNAME = "news"
PORTNUM = 5433

def most_popular_articles():
    db = psycopg2.connect(database=DBNAME, port=PORTNUM)
    c = db.cursor()
    c.execute("SELECT articles.title, COUNT(SUBSTRING(log.path, 10)) AS rank FROM articles JOIN log ON SUBSTRING(log.path, 10) LIKE articles.slug GROUP BY articles.title ORDER BY rank DESC LIMIT 3;")
    top3views = c.fetchall()
    db.close()
    return(top3views)

def author_rank():
    db = psycopg2.connect(database=DBNAME, port=PORTNUM)
    c = db.cursor()
    c.execute("SELECT au.name, autop.acount FROM (SELECT articles.author, COUNT(articles.author) AS acount FROM articles JOIN log ON SUBSTRING(log.path, 10) LIKE articles.slug GROUP BY articles.author ORDER BY acount DESC )autop JOIN authors au ON au.id = autop.author")
    authorrank = c.fetchall()
    db.close()
    return(authorrank)

def error_rate():
    db = psycopg2.connect(database=DBNAME, port=PORTNUM)
    c = db.cursor()
    c.execute("SELECT good.date, cast((good.ok * 1.0 )/total.all as decimal(10,2))*100 as erate FROM (SELECT date(time) as date, COUNT(status) AS ok FROM log WHERE status LIKE '200 OK' GROUP BY date) good, (SELECT date(time) as date, COUNT(status) AS all FROM log GROUP BY date) total WHERE good.date = total.date AND (good.ok * 1.0 )/total.all < 0.99 ORDER BY good.date; ")
    errors = c.fetchall()
    db.close()
    return(errors)


from datetime import datetime

from matplotlib.collections import LineCollection
import matplotlib.patheffects as mpatheffects
from matplotlib.pyplot import imread
import numpy as np

from ..units import concatenate

def add_timestamp(ax, time=None, x=0.99, y=-0.04, ha='right', high_contrast=False,
                  pretext='Created: ', time_format='%Y-%m-%dT%H:%M:%SZ', **kwargs):
    """Add a timestamp to a plot.

    Adds a timestamp to a plot, defaulting to the time of plot creation in ISO format.

    Parameters
    ----------
    ax : `matplotlib.axes.Axes`
        The `Axes` instance used for plotting
    time : `datetime.datetime` (or any object with a compatible ``strftime`` method)
        Specific time to be plotted - datetime.utcnow will be use if not specified
    x : float
        Relative x position on the axes of the timestamp
    y : float
        Relative y position on the axes of the timestamp
    ha : str
        Horizontal alignment of the time stamp string
    high_contrast : bool
        Outline text for increased contrast
    pretext : str
        Text to appear before the timestamp, optional. Defaults to 'Created: '
    time_format : str
        Display format of time, optional. Defaults to ISO format.

    Returns
    -------
    `matplotlib.text.Text`
        The `matplotlib.text.Text` instance created

    """
    if high_contrast:
        text_args = {'color': 'white',
                     'path_effects':
                         [mpatheffects.withStroke(linewidth=2, foreground='black')]}
    else:
        text_args = {}
    text_args.update(**kwargs)
    if not time:
        time = datetime.utcnow()
    timestr = time.strftime(time_format)
    # If we don't have a time string after that, assume xarray/numpy and see if item
    if not isinstance(timestr, str):
        timestr = timestr.item()
    return ax.text(x, y, pretext + timestr, ha=ha, transform=ax.transAxes, **text_args)

def _add_logo(fig, x=10, y=25, zorder=100, which='metpy', size='small', **kwargs):
    """Add the MetPy or Unidata logo to a figure.

    Adds an image to the figure.

    Parameters
    ----------
    fig : `matplotlib.figure`
       The `figure` instance used for plotting
    x : int
       x position padding in pixels
    y : float
       y position padding in pixels
    zorder : int
       The zorder of the logo
    which : str
       Which logo to plot 'metpy' or 'unidata'
    size : str
       Size of logo to be used. Can be 'small' for 75 px square or 'large' for
       150 px square.

    Returns
    -------
    `matplotlib.image.FigureImage`
       The `matplotlib.image.FigureImage` instance created

    """
    import importlib.resources

    fname_suffix = {'small': '_75x75.png',
                    'large': '_150x150.png'}
    fname_prefix = {'unidata': 'unidata',
                    'metpy': 'metpy'}
    try:
        fname = fname_prefix[which] + fname_suffix[size]
    except KeyError:
        raise ValueError('Unknown logo size or selection') from None

    with (importlib.resources.files('metpy.plots') / '_static' / fname).open('rb') as fobj:
        logo = imread(fobj)
    return fig.figimage(logo, x, y, zorder=zorder, **kwargs)

def add_metpy_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
    """Add the MetPy logo to a figure.

    Adds an image of the MetPy logo to the figure.

    Parameters
    ----------
    fig : `matplotlib.figure`
       The `figure` instance used for plotting
    x : int
       x position padding in pixels
    y : float
       y position padding in pixels
    zorder : int
       The zorder of the logo
    size : str
       Size of logo to be used. Can be 'small' for 75 px square or 'large' for
       150 px square.

    Returns
    -------
    `matplotlib.image.FigureImage`
       The `matplotlib.image.FigureImage` instance created

    """
    return _add_logo(fig, x=x, y=y, zorder=zorder, which='metpy', size=size, **kwargs)

def add_unidata_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs):
    """Add the Unidata logo to a figure.

    Adds an image of the MetPy logo to the figure.

    Parameters
    ----------
    fig : `matplotlib.figure`
       The `figure` instance used for plotting
    x : int
       x position padding in pixels
    y : float
       y position padding in pixels
    zorder : int
       The zorder of the logo
    size : str
       Size of logo to be used. Can be 'small' for 75 px square or 'large' for
       150 px square.

    Returns
    -------
    `matplotlib.image.FigureImage`
       The `matplotlib.image.FigureImage` instance created

    """
    return _add_logo(fig, x=x, y=y, zorder=zorder, which='unidata', size=size, **kwargs)

# Not part of public API
def colored_line(x, y, c, **kwargs):
    """Create a multi-colored line.

    Takes a set of points and turns them into a collection of lines colored by another array.

    Parameters
    ----------
    x : array-like
        x-axis coordinates
    y : array-like
        y-axis coordinates
    c : array-like
        values used for color-mapping
    kwargs : dict
        Other keyword arguments passed to :class:`matplotlib.collections.LineCollection`

    Returns
    -------
        The created :class:`matplotlib.collections.LineCollection` instance.

    """
    # Mask out any NaN values
    nan_mask = ~(np.isnan(x) | np.isnan(y) | np.isnan(c))
    x = x[nan_mask]
    y = y[nan_mask]
    c = c[nan_mask]

    # Paste values end to end
    points = concatenate([x, y])

    # Exploit numpy's strides to present a view of these points without copying.
    # Dimensions are (segment, start/end, x/y). Since x and y are concatenated back to back,
    # moving between segments only moves one item; moving start to end is only an item;
    # The move between x any moves from one half of the array to the other
    num_pts = points.size // 2
    final_shape = (num_pts - 1, 2, 2)
    final_strides = (points.itemsize, points.itemsize, num_pts * points.itemsize)
    segments = np.lib.stride_tricks.as_strided(points.m, shape=final_shape,
                                               strides=final_strides)

    # Create a LineCollection from the segments and set it to colormap based on c
    lc = LineCollection(segments, **kwargs)
    lc.set_array(getattr(c, 'magnitude', c))
    return lc

def convert_gempak_color(c, style='psc'):
    """Convert GEMPAK color numbers into corresponding Matplotlib colors.

    Takes a sequence of GEMPAK color numbers and turns them into
    equivalent Matplotlib colors. Various GEMPAK quirks are respected,
    such as treating negative values as equivalent to 0.

    Parameters
    ----------
    c : int or Sequence[int]
        GEMPAK color number(s)
    style : str, optional
        The GEMPAK 'device' to use to interpret color numbers. May be 'psc'
        (the default; best for a white background) or 'xw' (best for a black background).

    Returns
    -------
        List of strings of Matplotlib colors, or a single string if only one color requested.

    """
    def normalize(x):
        """Transform input x to an int in range 0 to 31 consistent with GEMPAK color quirks."""
        x = int(x)
        if x < 0 or x == 101:
            x = 0
        else:
            x %= 32
        return x

    # Define GEMPAK colors (Matplotlib doesn't appear to like numbered variants)
    cols = ['white',       # 0/32
            'black',       # 1
            'red',         # 2
            'green',       # 3
            'blue',        # 4
            'yellow',      # 5
            'cyan',        # 6
            'magenta',     # 7
            '#CD6839',     # 8 (sienna3)
            '#FF8247',     # 9 (sienna1)
            '#FFA54F',     # 10 (tan1)
            '#FFAEB9',     # 11 (LightPink1)
            '#FF6A6A',     # 12 (IndianRed1)
            '#EE2C2C',     # 13 (firebrick2)
            '#8B0000',     # 14 (red4)
            '#CD0000',     # 15 (red3)
            '#EE4000',     # 16 (OrangeRed2)
            '#FF7F00',     # 17 (DarkOrange1)
            '#CD8500',     # 18 (orange3)
            'gold',        # 19
            '#EEEE00',     # 20 (yellow2)
            'chartreuse',  # 21
            '#00CD00',     # 22 (green3)
            '#008B00',     # 23 (green4)
            '#104E8B',     # 24 (DodgerBlue4)
            'DodgerBlue',  # 25
            '#00B2EE',     # 26 (DeepSkyBlue2)
            '#00EEEE',     # 27 (cyan2)
            '#8968CD',     # 28 (MediumPurple3)
            '#912CEE',     # 29 (purple2)
            '#8B008B',     # 30 (magenta4)
            'bisque']      # 31

    if style != 'psc':
        if style == 'xw':
            cols[0] = 'black'
            cols[1] = 'bisque'
            cols[31] = 'white'
        else:
            raise ValueError('Unknown style parameter')

    try:
        c_list = list(c)
        res = [cols[normalize(x)] for x in c_list]
    except TypeError:
        res = cols[normalize(c)]
    return res


#다음과 같이 import를 사용할 수 있습니다.
#import math

def solution(a, b):
    # 여기에 코드를 작성해주세요.
    answer = 0
    prime = []
    cnt = set()

    for i in range(2, b + 1):
        flag = 0
        for j in range(2, i):
            if i % j == 0:
                flag = 1
                break
        if flag == 0:
            prime.append(i)

    for i in prime:
        if (i**2) >= a and (i**2) <= b:
            cnt.add(i**2)
        if (i**3) >= a and (i**3) <= b:
            cnt.add(i**3)
    answer = len(cnt)
    return answer

#아래는 테스트케이스 출력을 해보기 위한 코드입니다.
a =  6
b =  30
ret = solution(a, b)

#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은", ret, "입니다.")


# -*- coding: utf-8 -*-
# __author__ = 'qingchen.zhang'

import os
import subprocess
import re
import shutil
import pandas as pd
from biocluster.agent import Agent
from biocluster.tool import Tool
from biocluster.core.exceptions import OptionError
from mbio.packages.taxon.mask_taxon import mask_taxon
from mbio.packages.metaasv.common_function import link_dir

class PermanovaAgent(Agent):
    """
    metaasv Permanova分析
    与原来不一样的地方在于增加了多因素分析结果
    """
    def __init__(self, parent):
        super(PermanovaAgent, self).__init__(parent)
        options = [
            {"name": "abu_table", "type": "infile",
             "format": "meta.otu.otu_table, meta.otu.tax_summary_dir, toolapps.table"},
            {"name": "envtable", "type": "infile", "format": "meta.otu.group_table"},
            {"name": "permutations", "type": "int", "default": 999},
            {"name": "dis_method", "type": "string", "default": "bray"},
            {"name": "binary", "type": "string", "default": "false"}
        ]
        self.add_option(options)

    def check_options(self):
        """
        重写参数检查
        """
        if not self.option('abu_table').is_set:
            raise OptionError('必须提供丰度表')
        if not self.option('envtable').is_set:
            raise OptionError('必须提供环境因子表')

    def set_resource(self):
        """
        设置所需资源
        """
        self._cpu = 2
        self._memory = '10G'

    def end(self):
        super(PermanovaAgent, self).end()

class PermanovaTool(Tool):
    def __init__(self, config):
        super(PermanovaTool, self).__init__(config)
        self._version = '1.0'
        self.perl_path = "program/perl-5.24.0/bin/perl"
        self.script1_path = self.config.PACKAGE_DIR + "/metaasv/permanova_multiple.pl"
        self.permanova = self.config.PACKAGE_DIR + "/metaasv/permanova.pl"
        self.R_path = 'program/R-3.3.1/bin/Rscript'

    def run_permanova(self):
        """
        运行脚本 permanova.pl
        :return:
        """
        dir_name = os.path.join(self.work_dir, "permanova")
        if os.path.exists(dir_name):
            shutil.rmtree(dir_name)
        os.mkdir(dir_name)
        otu_table = self.option("abu_table").prop['path']
        self.name_to_name = mask_taxon(otu_table, self.work_dir + "/tmp_mask_otu.xls")
        otu_table = self.work_dir + '/tmp_mask_otu.xls'
        cmd = self.perl_path
        cmd += ' %s -i %s -env %s -o %s  -pe %s -d_method %s -binary %s -multi %s' % (
            self.script1_path, otu_table, os.path.join(self.work_dir, "env_table.xls"),
            self.work_dir + '/permanova/One-factor_PERMANOVA.xls', self.option("permutations"), self.option("dis_method"),
            self.option("binary"), self.work_dir + '/permanova/Multi-factor_PERMANOVA.xls')
        self.logger.info(cmd)
        command = self.add_command('cmd', cmd)
        command.run()
        self.wait(command)
        if command.return_code == 0:
            self.logger.info("permanova的r文件生成成功")
        else:
            self.set_error("permanova的r文件生成失败")
            raise Exception("permanova的r文件生成失败")
        cmd_1 = '%s %s' % (self.R_path, self.work_dir + "/cmd.r")
        self.logger.info(cmd_1)
        command1 = self.add_command('cmd_1', cmd_1)
        command1.run()
        self.wait(command1)
        if command1.return_code == 0:
            self.logger.info("R程序计算permanova成功")
        else:
            self.set_error("R程序计算permanova失败")
            raise Exception("R程序计算permanova失败")

    def dashrepl(self, matchobj):
        """
        替换名称
        """
        return self.name_to_name[matchobj.groups()[0]]

    def add_taxon(self, old_result, taxon_result):
        """
        description: 将旧注释的名称，根据词典替换成新注释名称
        """
        with open(old_result, "r") as f, open(taxon_result, "w") as w:
            # w.write(old_result)
            for i in f.readlines():
                # line = i.strip()
                new_line = re.sub(r"(name\d+)", self.dashrepl, i)
                w.write(new_line)

    def replace_env_name(self):
        """
        替换环境因子名称，避免因为环境因子顺序导致计算结果的差异
        :return:
        """
        self.env_name = {}
        env_table = os.path.join(self.work_dir, "env_table.xls")
        data = pd.read_table(self.option("envtable").prop['path'], sep="\t", header=0)
        data_list = list(data.columns)
        new_data_list = data_list[1:]
        new_data_list.sort()
        new_line = []
        for env_name in new_data_list:
            env_index = new_data_list.index(env_name)
            new_name = "name" + str(env_index + 1)
            if env_name not in self.env_name:
                self.env_name[new_name] = env_name
            if new_name not in new_line:
                new_line.append(new_name)
        all_list = [data_list[0]] + new_data_list
        new_all_list = [data_list[0]] + new_line
        data = data[all_list]
        data.columns = new_all_list
        self.logger.info("correlation_relationship: {}".format(self.env_name))
        data.to_csv(env_table, index=0, sep="\t")

        # with open(self.option("envtable").prop['path'], "r") as f, open(env_table, "w") as w:
        #     line = f.readline()
        #     line = line.strip().split("\t")
        #
        #     for env_name in line[1:]:
        #         env_index = line.index(env_name)
        #         new_name = "name" + str(env_index)
        #         if env_name not in self.env_name:
        #             self.env_name[new_name] = env_name
        #         if new_name not in new_line:
        #             new_line.append(new_name)
        #     w.write(line[0] + "\t" + "\t".join(new_line) + "\n")
        #     for lin in f:
        #         w.write(lin)

    def replace_name(self, infile1, infile2,type):
        """
        对最后的多因素计算结果添加名称
        原因是：最后的多因素结果可能会有部分的因子计算不出结果，导致结果错位
        解决方案是：根据统计结果，对多因素结果进行添加名称
        :param infile1: 统计结果表
        :param infile2: 多因素计算结果表
        :return:
        """
        if type in ["multiple"]:
            tmp_path = os.path.join(self.work_dir, "tmp.xls")
            with open(infile1, "r") as f, open(infile2, "r") as r, open(tmp_path, 'w') as w:
                lines1 = f.readlines()
                lines2 = r.readlines()
                w.write(lines2[0])
                for line in lines1[1:]:
                    line1 = line.strip().split("\t")
                    for lin in lines2[1:]:
                        line2 = lin.strip().split("\t")
                        if line1[2] == line2[1]:
                            w.write(lin)
                            break
            if os.path.exists(infile2):
                os.remove(infile2)
            if os.path.exists(tmp_path):
                os.rename(tmp_path, infile2)
        out_path = os.path.join(self.work_dir, "last_result.xls")
        factor_name_list = []
        with open(infile1, "r") as f:
            lines = f.readlines()
            for line in lines[1:]:
                line = line.strip().split("\t")
                try:
                    factor = eval(line[0])
                except:
                    factor = line[0]
                if factor in self.env_name:
                    new_factor = self.env_name[factor]
                    if new_factor not in factor_name_list:
                        factor_name_list.append(new_factor)
        if type in ["multiple"]:
            factor_name_list.append("Residuals")
            factor_name_list.append("Total")
        with open(infile2, "r") as r, open(out_path, 'w') as w:
            lins = r.readlines()
            header = lins[0].strip().split('\t')
            if type in ["multiple"]:
                new_header = ["Name"] + header
            else:
                new_header = header
            header_string = "\t".join(new_header)
            w.write(header_string+"\n")
            n = 0
            for lin in lins[1:]:
                lin = lin.strip().split("\t")
                if type in ["multiple"]:
                    new_line = [factor_name_list[n]] + lin
                else:
                    new_line = [factor_name_list[n]] + lin[1:]
                line_string = "\t".join(new_line)
                w.write(line_string+"\n")
                n += 1
        if os.path.exists(infile2):
            os.remove(infile2)
        if os.path.exists(out_path):
            os.rename(out_path, infile2)

    def run(self):
        """
        运行
        :return:
        """
        super(PermanovaTool, self).run()
        self.replace_env_name()
        self.run_permanova()
        self.replace_name(os.path.join(self.work_dir, "test_result.xls"), os.path.join(self.work_dir, "permanova","Multi-factor_PERMANOVA.xls"), "multiple")
        self.replace_name(os.path.join(self.work_dir, "permanova","One-factor_PERMANOVA.xls"), os.path.join(self.work_dir, "permanova","One-factor_PERMANOVA.xls"), "single")

        self.set_output()

    def set_output(self):
        """
        设置结果文件目录
        :return:
        """
        link_dir(os.path.join(self.work_dir,"permanova"), self.output_dir)
        self.end()


from django.urls import path,include
from . import views
urlpatterns = [
    path('add/', views.addtask),
    path('index/',views.index),
    path('task/',views.task),
    path('result/',views.result),
    path('detail/',views.detail),
]


import math
from functools import partial
import itertools
from timeit import default_timer as timer

from mpl_toolkits import mplot3d
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams.update({'font.size': 18})
from matplotlib.colors import ListedColormap
import pandas as pd
import seaborn as sns

import random
import numpy as np

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import spectral_inference_networks as spin

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import MultivariateNormal

from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification

from utils import nystrom, build_mlp_given_config, init_NN, ParallelMLP
from nngpk import NNGPKernel

class NeuralEigenFunctions(nn.Module):
	def __init__(self, k, kernel_type, input_size, hidden_size, num_layers,
				 output_size=1, momentum=0.9, normalize_over=[0]):
		super(NeuralEigenFunctions, self).__init__()
		self.momentum = momentum
		self.normalize_over = normalize_over
		self.functions = nn.ModuleList()
		for i in range(k):
			function = build_mlp_given_config(nonlinearity=kernel_type,
											  input_size=input_size,
											  hidden_size=hidden_size,
											  output_size=output_size,
											  num_layers=num_layers,
											  bias=True)
			self.functions.append(function)
		self.register_buffer('eigennorm', torch.zeros(k))
		self.register_buffer('num_calls', torch.Tensor([0]))

	def forward(self, x):
		ret_raw = torch.cat([f(x) for f in self.functions], 1)
		if self.training:
			norm_ = ret_raw.norm(dim=self.normalize_over) / math.sqrt(
				np.prod([ret_raw.shape[dim] for dim in self.normalize_over]))
			with torch.no_grad():
				if self.num_calls == 0:
					self.eigennorm.copy_(norm_.data)
				else:
					self.eigennorm.mul_(self.momentum).add_(
						norm_.data, alpha = 1-self.momentum)
				self.num_calls += 1
		else:
			norm_ = self.eigennorm
		return ret_raw / norm_

def our(X, k, kernel, kernel_type, w_var_list, b_var_list):
	hidden_size = 32
	num_layers = len(w_var_list)
	optimizer_type = 'Adam'
	lr = 1e-3
	momentum = 0.9
	num_iterations = 2000
	num_samples = 10000
	B = min(128, X.shape[0])

	random_model =  build_mlp_given_config(nonlinearity=kernel_type,
										   input_size=X.shape[-1],
										   hidden_size=16,
										   output_size=1,
										   bias=True,
										   num_layers=num_layers)
	samples = []
	with torch.no_grad():
		for _ in range(num_samples):
			init_NN(random_model, w_var_list, b_var_list)
			samples.append(random_model(X))
	samples = torch.cat(samples, -1).T

	start = timer()
	nef = NeuralEigenFunctions(k, kernel_type, X.shape[-1], hidden_size, num_layers)
	print(nef.functions[0])
	if optimizer_type == 'Adam':
		optimizer = torch.optim.Adam(nef.parameters(), lr=lr)
	elif optimizer_type == 'RMSprop':
		optimizer = torch.optim.RMSprop(nef.parameters(), lr=lr, momentum=momentum)
	else:
		optimizer = torch.optim.SGD(nef.parameters(), lr=lr, momentum=momentum)

	nef.train()
	eigenvalues_our = None
	for ite in range(num_iterations):
		idx = np.random.choice(X.shape[0], B, replace=False)
		samples_batch = samples[:, idx]
		psis_X = nef(X[idx])
		with torch.no_grad():
			samples_batch_psis = samples_batch @ psis_X
			psis_K_psis = samples_batch_psis.T @ samples_batch_psis / num_samples
			mask = torch.eye(k, device=psis_X.device) - \
				(psis_K_psis / psis_K_psis.diag()).tril(diagonal=-1).T
			grad = samples_batch.T @ (samples_batch_psis @ mask / num_samples)

			if eigenvalues_our is None:
				eigenvalues_our = psis_K_psis.diag() / (B**2)
			else:
				eigenvalues_our.mul_(0.9).add_(psis_K_psis.diag() / (B**2), alpha = 0.1)

		optimizer.zero_grad()
		psis_X.backward(-grad)
		optimizer.step()
	end = timer()
	return eigenvalues_our, nef, end - start

def spin_tf(X, X_val, k, kernel, kernel_type):

	lr = 1e-3
	num_iterations = 2000
	B = min(128, X.shape[0])

	linop = spin.KernelOperator(kernel.make_relu_kernel_tf()
		if kernel_type == 'relu' else kernel.make_erf_kernel_tf())

	start = timer()
	# Create variables for simple MLP
	w1 = tf.Variable(tf.random.normal([k, 32, X.shape[1]], 0, math.sqrt(2./X.shape[1])))
	w2 = tf.Variable(tf.random.normal([k, 32, 32], 0, math.sqrt(2./32)))
	w3 = tf.Variable(tf.random.normal([k, 1, 32], 0, math.sqrt(2./32)))

	b1 = tf.Variable(tf.zeros([k, 32, 1]))
	b2 = tf.Variable(tf.zeros([k, 32, 1]))
	b3 = tf.Variable(tf.zeros([k, 1, 1]))

	# Create function to construct simple MLP
	def network(x):
	  h1 = tf.tensordot(w1, x, [[2], [1]]) + b1
	  if kernel_type == 'erf':
		  h1_act = tf.math.erf(h1)
	  elif kernel_type == 'relu':
		  h1_act = tf.nn.relu(h1)
	  else:
		  raise NotImplementedError

	  h2 = tf.matmul(w2, h1_act) + b2
	  if kernel_type == 'erf':
		  h2_act = tf.math.erf(h2)
	  elif kernel_type == 'relu':
		  h2_act = tf.nn.relu(h2)
	  else:
		  raise NotImplementedError

	  h3 = tf.matmul(w3, h2_act) + b3
	  return tf.squeeze(tf.transpose(h3, perm=[2, 1, 0]))

	optim = tf.train.AdamOptimizer(learning_rate=lr)
	# Constructs the internal training ops for spectral inference networks.
	spectral_net = spin.SpectralNetwork(
	    linop,
	    network,
	    X,
	    [w1, w2, w3, b1, b2, b3],
		B, decay=0.99)

	# Trivial defaults for logging and stats hooks.
	logging_config = {
	    'config': {},
	    'log_image_every': 100000000,
	    'save_params_every': 100000000,
	    'saver_path': './tmp',
	    'saver_name': 'example',
	}

	stats_hooks = {
	    'create': spin.util.create_default_stats,
	    'update': spin.util.update_default_stats,
	}

	# Executes the training of spectral inference networks.
	stats, outputs = spectral_net.train(
	    optim,
	    num_iterations,
	    logging_config,
	    stats_hooks,
		data_for_plotting = tf.constant(X_val))
	end = timer()
	return outputs, end - start

def main():
	# set random seed
	seed = 42
	random.seed(seed)
	np.random.seed(seed)
	torch.manual_seed(seed)
	torch.backends.cudnn.deterministic = True
	torch.backends.cudnn.benchmark = False

	# setup the nngp kernel
	kernel_type = 'erf'
	w_var_list = [2., 2., 2.]
	b_var_list = [1, 1, 1]

	# general settings
	num_alldata = 1000
	k = 3
	# dataset settings
	dataset = 'circles'
	if dataset == 'two_moon':
		X, y = make_moons(num_alldata, noise=0.04, random_state=seed)
		kernel_type = 'relu'
	elif dataset == 'circles':
		X, y = make_circles(num_alldata, noise=0.04, factor=0.5, random_state=seed)
	else:
		raise NotImplementedError

	kernel = NNGPKernel(kernel_type=kernel_type, w_var_list=w_var_list, b_var_list=b_var_list)

	X = StandardScaler().fit_transform(X)
	x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
	y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + 0.6
	X = torch.from_numpy(X).float()

	# plot the dataset
	figure = plt.figure(figsize=(15, 5))
	cm = plt.cm.RdBu
	cm_bright = ListedColormap(['#FF0000', '#0000FF'])
	ax = figure.add_subplot(131)
	ax.set_title("Input data")
	# Plot the training points
	ax.scatter(X[:, 0], X[:, 1], c=y, cmap=cm_bright,
			   edgecolors='k')
	ax.set_xlim(x_min, x_max)
	ax.set_ylim(y_min, y_max)
	ax.set_xticks(())
	ax.set_yticks(())
	ax.spines['right'].set_visible(False)
	ax.spines['top'].set_visible(False)
	ax.spines['left'].set_visible(False)
	ax.spines['bottom'].set_visible(False)
	ax.set_axisbelow(True)

	eigenvalues_nystrom, eigenfuncs_nystrom, c_nystrom = nystrom(X, k, kernel)
	eigenvalues_our, nef, c_our = our(X, k, kernel, kernel_type, w_var_list, b_var_list)

	print("Eigenvalues estimated by nystrom method:")
	print(eigenvalues_nystrom)
	print("Eigenvalues estimated by our method:")
	print(eigenvalues_our)
	print("Time comparison {} vs. {}".format(c_nystrom, c_our))

	nef.eval()
	with torch.no_grad():
		X_projected_by_nystrom = eigenfuncs_nystrom(X)
		X_projected_by_our = nef(X)
		print(X_projected_by_nystrom[: 5])
		print(X_projected_by_our[: 5])

	X_projected_by_spin, c_spin = spin_tf(X, X, k, kernel, kernel_type)

	ax = figure.add_subplot(132, projection='3d')
	ax.set_title("Projected by our method")
	X_projected_by_our_0 = -X_projected_by_our[:, 0] if dataset == 'two_moon' else X_projected_by_our[:, 0]
	X_projected_by_our_1 = -X_projected_by_our[:, 1] if dataset == 'two_moon' else X_projected_by_our[:, 1]
	X_projected_by_our_2 = X_projected_by_our[:, 2]
	ax.scatter(X_projected_by_our_0, X_projected_by_our_1, X_projected_by_our_2, c=y, cmap=cm_bright,
			   edgecolors='k')
	ax.grid(True)
	plt.setp( ax.get_xticklabels(), visible=False)
	plt.setp( ax.get_yticklabels(), visible=False)
	plt.setp( ax.get_zticklabels(), visible=False)

	ax = figure.add_subplot(133, projection='3d')
	ax.set_title("Projected by SpIN")
	X_projected_by_spin_0 = X_projected_by_spin[:, 0] if dataset == 'two_moon' else X_projected_by_spin[:, 0]
	X_projected_by_spin_1 = -X_projected_by_spin[:, 1] if dataset == 'two_moon' else X_projected_by_spin[:, 1]
	X_projected_by_spin_2 = X_projected_by_spin[:, 2]
	ax.scatter(X_projected_by_spin_0, X_projected_by_spin_1, X_projected_by_spin_2, c=y, cmap=cm_bright,
			   edgecolors='k')
	ax.grid(True)
	plt.setp( ax.get_xticklabels(), visible=False)
	plt.setp( ax.get_yticklabels(), visible=False)
	plt.setp( ax.get_zticklabels(), visible=False)

	figure.tight_layout()
	figure.savefig('nngp_plots/{}.pdf'.format(dataset), format='pdf', dpi=1000, bbox_inches='tight')

if __name__ == '__main__':
	main()


def summ_number(n):
    summ_n = 0
    while n != 0:
        last_num = n % 10
        summ_n += last_num
        n //= 10
    return summ_n

def count_number(n):
    count = 0
    while n != 0:
        count += 1
        n //= 10
    return count

n = int(input('Введите число: '))
summ_number(n)
count_number(n)

summa = summ_number(n)
count = count_number(n)
print('Сумма цифр:', summa)
print('Кол-во цифр в числе:', count)
print('Разность суммы и кол-ва цифр:', summa - count)

# зачёт!


if __name__ == '__main__':
	n, m = map(int, input().split())
	nums = [i + 1 for i in range(n)]
	seq = []  # 用于存储操作序列
	for _ in range(m):
		p, q = map(int, input().split())
		if p == 0:
			while seq and seq[-1][0] == 0:  # 如果是连续的 p = 0，只取最大的 q
				q = max(q, seq[-1][1])
				seq.pop()
			while len(seq) > 1 and seq[-2][1] <= q:  # 如果此次前缀降序的右边界大于上一次前缀降序的有边界，可以省略在此之前的两次操作
				seq.pop()
				seq.pop()
			seq.append((0, q))
		elif seq:  # seq 不为空保证这是有一个 p = 0 之后的 p = 1 操作
			while seq and seq[-1][0] == 1:  # 如果是连续的 p = 1，只取最小的 q
				q = min(q, seq[-1][1])
				seq.pop()
			while len(seq) > 1 and seq[-2][1] >= q:  # 如果此次后缀升序的左边界小于上一次后缀升序的有边界，可以省略在此之前的两次操作
				seq.pop()
				seq.pop()
			seq.append((1, q))

	k, left, right = n, 1, n
	for i in range(len(seq)):
		if seq[i][0] == 0:  # 前缀降序
			while right > seq[i][1] and left <= right:
				nums[right - 1] = k		# 从后往前设置
				right -= 1
				k -= 1
		else:  # 后缀升序
			while left < seq[i][1] and left <= right:
				nums[left - 1] = k		# 从前往后设置
				left += 1
				k -= 1
		if left > right:
			break

	if len(seq) % 2:   # 最后一次操作为前缀降序
		while left <= right:
			nums[left - 1] = k
			left += 1
			k -= 1
	else:				# 最后一次操作为后缀升序
		while left <= right:
			nums[right - 1] = k
			right -= 1
			k -= 1

	print(' '.join(map(str, nums)))


# -*- coding: utf-8 -*-
# @Author: lnorb.com
# @Date:   2021-12-27 04:05:23
# @Last Modified by:   lnorb.com
# @Last Modified time: 2022-08-08 14:22:10

import re
from pathlib import Path

from kivy.app import App
from kivy.utils import platform

mobile = platform in ("ios", "android")
ios = platform == "ios"
android = platform == "android"
desktop = platform not in ("ios", "android")

def prefs_col(name):
    """
    Get a preference value in the
    form section.key as an RGBA list.
    """
    app = App.get_running_app()
    section, key = name.split(".")
    col = app.config[section][key]
    if "#" in col:
        if len(col) == 7:
            col += "ff"
        r, g, b, a = list(int(col[i : i + 2], base=16) / 255 for i in range(1, 8, 2))
        return r, g, b, a
    return eval(col)

def pref(name):
    """
    Get a preference value in the
    form section.key.
    """
    app = App.get_running_app()
    if app:
        section, key = name.split(".")
        if section not in app.config:
            print(f"CONFIG SECTION NOT FOUND: {section}")
            return ""
        if app.config[section][key] == "False":
            return False
        if app.config[section][key] == "True":
            return True
        try:
            return float(app.config[section][key])
        except:
            return app.config[section][key]

def set_string_pref(name, val):
    app = App.get_running_app()
    if app:
        section, key = name.split(".")
    app.config[section][key] = val
    app.config.write()

def pref_path(name):
    app = App.get_running_app()
    return Path(app.user_data_dir) / pref(f"path.{name}")

class hashabledict(dict):
    def __hash__(self):
        return hash(tuple(sorted(self.items())))

def get_available_nodes():
    from orb.core_ui.app_common import AppCommon
    path = AppCommon._get_user_data_dir_static()
    data_dir = Path(path)
    nodes = []
    for x in data_dir.glob("orb_*"):
        m = re.match(r"^orb_([a-zA-Z0-9]{66})$", x.name)
        if m and x.is_dir():
            nodes.append(m.group(1))
    return nodes


#!/bin/python3

import os
import sys

#
# Complete the timeConversion function below.
#
def timeConversion(s):
    #
    # Write your code here.
    if ('PM' in s):
       t=s.split(":")
       hh=t[0]
       mm=t[1]
       ss=t[2]
       print(t[1])
      #print(hh[0])
      # hh=int(hh[0])+12
       mm=int(s[3])
       print (mm)

if ( __name__ == '__main__' ):

    f = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    f.write(result + '\n')

    f.close()


import numpy as np
import torch
import torch.nn.functional as F
from pyannote.audio.generators.speaker import SpeechSegmentGenerator
from pyannote.audio.embedding.utils import to_condensed, pdist
from scipy.spatial.distance import squareform
from pyannote.metrics.binary_classification import det_curve
from collections import deque
from pyannote.audio.train import Trainer
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence

class TripletLoss(Trainer):
    """

    delta = d(anchor, positive) - d(anchor, negative)

    * with 'positive' clamping:
        loss = max(0, delta + margin x D)
    * with 'sigmoid' clamping:
        loss = sigmoid(10 * delta)

    where d(., .) varies in range [0, D] (e.g. D=2 for euclidean distance).

    Parameters
    ----------
    duration : float, optional
        Use fixed duration segments with this `duration`.
        Defaults (None) to using variable duration segments.
    min_duration : float, optional
        In case `duration` is None, set segment minimum duration.
    max_duration : float, optional
        In case `duration` is None, set segment maximum duration.
    metric : {'euclidean', 'cosine', 'angular'}, optional
        Defaults to 'cosine'.
    margin: float, optional
        Margin multiplicative factor. Defaults to 0.2.
    clamp : {'positive', 'sigmoid', 'softmargin'}, optional
        Defaults to 'positive'.
    sampling : {'all', 'hard', 'negative'}, optional
        Triplet sampling strategy.
    per_label : int, optional
        Number of sequences per speaker in each batch. Defaults to 3.
    label_min_duration : float, optional
        Remove speakers with less than `label_min_duration` seconds of speech.
        Defaults to 0 (i.e. keep them all).
    per_fold : int, optional
        If provided, sample triplets from groups of `per_fold` speakers at a
        time. Defaults to sample triplets from the whole speaker set.
    parallel : int, optional
        Number of prefetching background generators. Defaults to 1.
        Each generator will prefetch enough batches to cover a whole epoch.
        Set `parallel` to 0 to not use background generators.
    optimizer : {'sgd', 'rmsprop', 'adam'}
        Defaults to 'rmsprop'.
    learning_rate : float, optional
        Defaults to 1e-2.
    enable_backtrack : bool, optional
        Defaults to True.
    """

    def __init__(self, duration=None, min_duration=None, max_duration=None,
                 metric='cosine', margin=0.2, clamp='positive',
                 sampling='all', per_label=3, per_fold=None, parallel=1,
                 label_min_duration=0.,
                 optimizer='rmsprop', learning_rate=1e-2,
                 enable_backtrack=True):

        super(TripletLoss, self).__init__()

        self.metric = metric
        self.margin = margin

        self.margin_ = self.margin * self.max_distance

        if clamp not in {'positive', 'sigmoid', 'softmargin'}:
            msg = "'clamp' must be one of {'positive', 'sigmoid', 'softmargin'}."
            raise ValueError(msg)
        self.clamp = clamp

        if sampling not in {'all', 'hard', 'negative'}:
            msg = "'sampling' must be one of {'all', 'hard', 'negative'}."
            raise ValueError(msg)
        self.sampling = sampling

        self.per_fold = per_fold
        self.per_label = per_label
        self.label_min_duration = label_min_duration

        self.duration = duration
        self.min_duration = min_duration
        self.max_duration = max_duration

        self.parallel = parallel
        self.optimizer = optimizer
        self.learning_rate = learning_rate
        self.enable_backtrack = enable_backtrack

    @property
    def max_distance(self):
        if self.metric == 'cosine':
            return 2.
        elif self.metric == 'angular':
            return np.pi
        elif self.metric == 'euclidean':
            # FIXME. incorrect if embedding are not unit-normalized
            return 2.
        else:
            msg = "'metric' must be one of {'euclidean', 'cosine', 'angular'}."
            raise ValueError(msg)

    def pdist(self, fX):
        """Compute pdist à-la scipy.spatial.distance.pdist

        Parameters
        ----------
        fX : (n, d) torch.Tensor
            Embeddings.

        Returns
        -------
        distances : (n * (n-1) / 2,) torch.Tensor
            Condensed pairwise distance matrix
        """

        n_sequences, _ = fX.size()
        distances = []

        for i in range(n_sequences - 1):

            if self.metric in ('cosine', 'angular'):
                d = 1. - F.cosine_similarity(
                    fX[i, :].expand(n_sequences - 1 - i, -1),
                    fX[i+1:, :], dim=1, eps=1e-8)

                if self.metric == 'angular':
                    d = torch.acos(torch.clamp(1. - d, -1 + 1e-6, 1 - 1e-6))

            elif self.metric == 'euclidean':
                d = F.pairwise_distance(
                    fX[i, :].expand(n_sequences - 1 - i, -1),
                    fX[i+1:, :], p=2, eps=1e-06).view(-1)

            distances.append(d)

        return torch.cat(distances)

    def batch_hard(self, y, distances):
        """Build triplet with both hardest positive and hardest negative

        Parameters
        ----------
        y : list
            Sequence labels.
        distances : (n * (n-1) / 2,) torch.Tensor
            Condensed pairwise distance matrix

        Returns
        -------
        anchors, positives, negatives : list of int
            Triplets indices.
        """

        anchors, positives, negatives = [], [], []

        distances = squareform(self.to_numpy(distances))
        y = np.array(y)

        for anchor, y_anchor in enumerate(y):

            d = distances[anchor]

            # hardest positive
            pos = np.where(y == y_anchor)[0]
            pos = [p for p in pos if p != anchor]
            positive = int(pos[np.argmax(d[pos])])

            # hardest negative
            neg = np.where(y != y_anchor)[0]
            negative = int(neg[np.argmin(d[neg])])

            anchors.append(anchor)
            positives.append(positive)
            negatives.append(negative)

        return anchors, positives, negatives

    def batch_negative(self, y, distances):
        """Build triplet with hardest negative

        Parameters
        ----------
        y : list
            Sequence labels.
        distances : (n * (n-1) / 2,) torch.Tensor
            Condensed pairwise distance matrix

        Returns
        -------
        anchors, positives, negatives : list of int
            Triplets indices.
        """

        anchors, positives, negatives = [], [], []

        distances = squareform(self.to_numpy(distances))
        y = np.array(y)

        for anchor, y_anchor in enumerate(y):

            # hardest negative
            d = distances[anchor]
            neg = np.where(y != y_anchor)[0]
            negative = int(neg[np.argmin(d[neg])])

            for positive in np.where(y == y_anchor)[0]:
                if positive == anchor:
                    continue

                anchors.append(anchor)
                positives.append(positive)
                negatives.append(negative)

        return anchors, positives, negatives

    def batch_all(self, y, distances):
        """Build all possible triplet

        Parameters
        ----------
        y : list
            Sequence labels.
        distances : (n * (n-1) / 2,) torch.Tensor
            Condensed pairwise distance matrix

        Returns
        -------
        anchors, positives, negatives : list of int
            Triplets indices.
        """

        anchors, positives, negatives = [], [], []

        for anchor, y_anchor in enumerate(y):
            for positive, y_positive in enumerate(y):

                # if same embedding or different labels, skip
                if (anchor == positive) or (y_anchor != y_positive):
                    continue

                for negative, y_negative in enumerate(y):

                    if y_negative == y_anchor:
                        continue

                    anchors.append(anchor)
                    positives.append(positive)
                    negatives.append(negative)

        return anchors, positives, negatives

    def triplet_loss(self, distances, anchors, positives, negatives,
                     return_delta=False):
        """Compute triplet loss

        Parameters
        ----------
        distances : torch.Tensor
            Condensed matrix of pairwise distances.
        anchors, positives, negatives : list of int
            Triplets indices.
        return_delta : bool, optional
            Return delta before clamping.

        Returns
        -------
        loss : torch.Tensor
            Triplet loss.
        """

        # estimate total number of embeddings from pdist shape
        n = int(.5 * (1 + np.sqrt(1 + 8 * len(distances))))
        n = [n] * len(anchors)

        # convert indices from squared matrix
        # to condensed matrix referential
        pos = list(map(to_condensed, n, anchors, positives))
        neg = list(map(to_condensed, n, anchors, negatives))

        # compute raw triplet loss (no margin, no clamping)
        # the lower, the better
        delta = distances[pos] - distances[neg]

        # clamp triplet loss
        if self.clamp == 'positive':
            loss = torch.clamp(delta + self.margin_, min=0)

        elif self.clamp == 'softmargin':
            loss = torch.log1p(torch.exp(delta))

        elif self.clamp == 'sigmoid':
            # TODO. tune this "10" hyperparameter
            # TODO. log-sigmoid
            loss = F.sigmoid(10 * (delta + self.margin_))

        # return triplet losses
        if return_delta:
            return loss, delta.view((-1, 1)), pos, neg
        else:
            return loss

    def get_batch_generator(self, feature_extraction):
        return SpeechSegmentGenerator(
            feature_extraction, label_min_duration=self.label_min_duration,
            per_label=self.per_label, per_fold=self.per_fold,
            duration=self.duration, min_duration=self.min_duration,
            max_duration=self.max_duration, parallel=self.parallel)

    def aggregate(self, batch):
        return batch

    def on_train_start(self, model, batches_per_epoch=None, **kwargs):
        self.log_positive_ = deque([], maxlen=batches_per_epoch)
        self.log_negative_ = deque([], maxlen=batches_per_epoch)
        self.log_delta_ = deque([], maxlen=batches_per_epoch)
        self.log_norm_ = deque([], maxlen=batches_per_epoch)

    def batch_loss(self, batch, model, device, writer=None, **kwargs):

        lengths = torch.tensor([len(x) for x in batch['X']])
        variable_lengths = len(set(lengths)) > 1

        if variable_lengths:

            sorted_lengths, sort = torch.sort(lengths, descending=True)
            _, unsort = torch.sort(sort)

            sequences = [torch.tensor(batch['X'][i],
                                      dtype=torch.float32,
                                      device=device) for i in sort]
            padded = pad_sequence(sequences, batch_first=True, padding_value=0)
            packed = pack_padded_sequence(padded, sorted_lengths,
                                          batch_first=True)
            batch['X'] = packed
        else:
            batch['X'] = torch.tensor(np.stack(batch['X']),
                                      dtype=torch.float32,
                                      device=device)

        # forward pass
        fX = model(batch['X'])

        if variable_lengths:
            fX = fX[unsort]

        # log embedding norms
        if writer is not None:
            norm_npy = np.linalg.norm(self.to_numpy(fX), axis=1)
            self.log_norm_.append(norm_npy)

        batch['fX'] = fX
        batch = self.aggregate(batch)

        fX = batch['fX']
        y = batch['y']

        # pre-compute pairwise distances
        distances = self.pdist(fX)

        # sample triplets
        triplets = getattr(self, 'batch_{0}'.format(self.sampling))
        anchors, positives, negatives = triplets(y, distances)

        # compute loss for each triplet
        losses, deltas, _, _ = self.triplet_loss(
            distances, anchors, positives, negatives,
            return_delta=True)

        if writer is not None:
            pdist_npy = self.to_numpy(distances)
            delta_npy = self.to_numpy(deltas)
            same_speaker = pdist(y.reshape((-1, 1)), metric='equal')
            self.log_positive_.append(pdist_npy[np.where(same_speaker)])
            self.log_negative_.append(pdist_npy[np.where(~same_speaker)])
            self.log_delta_.append(delta_npy)

        # average over all triplets
        return torch.mean(losses)

    def on_epoch_end(self, iteration, writer=None, **kwargs):

        if writer is None:
            return

        # log intra class vs. inter class distance distributions
        log_positive = np.hstack(self.log_positive_)
        log_negative = np.hstack(self.log_negative_)
        writer.add_histogram(
            'train/distance/intra_class', log_positive,
            global_step=iteration, bins='doane')
        writer.add_histogram(
            'train/distance/inter_class', log_negative,
            global_step=iteration, bins='doane')

        # log same/different experiment on training samples
        _, _, _, eer = det_curve(
            np.hstack([np.ones(len(log_positive)),
                       np.zeros(len(log_negative))]),
            np.hstack([log_positive, log_negative]),
            distances=True)
        writer.add_scalar('train/eer', eer,
                          global_step=iteration)

        # log raw triplet loss (before max(0, .))
        log_delta = np.vstack(self.log_delta_)
        writer.add_histogram(
            'train/triplet/delta', log_delta,
            global_step=iteration, bins='doane')

        # log distribution of embedding norms
        log_norm = np.hstack(self.log_norm_)
        writer.add_histogram(
            'train/embedding/norm', log_norm,
            global_step=iteration, bins='doane')


# -*- coding: utf-8 -*-
"""
Created on Sat Aug 22 10:06:54 2020

@author: saura
"""
'''
Question 13
    Write a program that accepts a sentence and calculate the number of letters and digits.
    Suppose the following input is supplied to the program:
hello world! 123
    Then, the output should be:
LETTERS 10
DIGITS 3
'''
message = "hello world! 123"

num = '0123456789'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet = alphabet + alphabet.upper()

count_num = 0
count_alpha = 0

for item in message:
    for number in num:
        if number == item:
            count_num += 1
            break

    for letter in alphabet:
        if letter == item:
            count_alpha += 1
            break

print(f"Letters: {count_alpha}")
print(f"Digits: {count_num}")

#######################################################

word = "hello world! 123"
letter,digit = 0,0

for i in word:
    if ('a'<=i and i<='z') or ('A'<=i and i<='Z'):
        letter+=1
    if '0'<=i and i<='9':
        digit+=1

print("LETTERS {0}\nDIGITS {1}".format(letter,digit))

########################################################

letter, digit = 0,0

for i in word:
    if i.isalpha(): # returns True if alphabet
        letter += 1
    elif i.isnumeric(): # returns True if numeric
        digit += 1
print(f"LETTERS {letter}\nDIGITS {digit}")

########################################################

import re
counter = {"LETTERS":len(re.findall("[a-zA-Z]", word)), "NUMBERS":len(re.findall("[0-9]", word))}
print(counter)


import os, sys, multiprocessing

'''
Name: admpipe.py
Description:
    Run ADMIXTURE analysis automatically in multiprocessing way, with 10 fold
    cross validation error,and plot the results automatically.
Input: the genofile in eigenstrat prefix.geno format
Output: prefix.k.P prefix.k.Q prefix_k.log prefix_adm.pdf
Arguments:
    prefix: the prefix for input and output file
    maxk: the max K to run ADMIXTURE
'''

def write_plot(prefix, maxk):
    outf = '{}_adm.r'.format(prefix)
    with open(outf, 'w') as out:
        out.write('pdf("{}_adm.pdf", width=8, height=4)\n'.format(prefix))
        for k in range(2,maxk+1):
            out.write('d<-read.table("{}.{}.Q")\n'.format(prefix, k))
            out.write('barplot(t(as.matrix(d)), col=1:{}, space=0, border=NA, ylab="Ancestry")\n'.format(k))
        out.write('dev.off()\n')
    print('Write plot script to {}'.format(outf))

def worker(prefix, k):
    cmd = 'admixture --cv=10 {0}.geno {1} > {0}_{1}.log'.format(prefix,k)
    print('job-{}: {}'.format(k,cmd))
    os.system(cmd)

def run_adm(prefix, maxk=2):
    jobs=[]
    for k in range(1, maxk+1):
        p = multiprocessing.Process(name='job-'+repr(k),target=worker, args=(prefix,k))
        jobs.append(p)
        p.start()
    for j in jobs:
        j.join()
        print('{}: Finished'.format(j.name))
    write_plot(prefix, maxk)
    os.system('Rscript {}_adm.r'.format(prefix))
    print('Find the results in {}_adm.pdf'.format(prefix))
    print('Please referrence to the cross validation error below:')
    os.system('grep CV {}_*.log'.format(prefix))

if __name__=='__main__':
    if len(sys.argv)>2:
        maxk = int(sys.argv[2])
        run_adm(sys.argv[1], maxk)
    elif len(sys.argv)>1:
        run_adm(sys.argv[1])
    else:
        print('Usage: python {} <prefix> [maxk]'.format(sys.argv[0]))


# load library
import urllib.request
import requests
import os

outpath = "C:/알약jpg/"
if not os.path.isdir(outpath):
    os.makedirs(outpath)

url = 'http://www.pharm.or.kr/images/sb_photo/small/'
url2 = "http://dikweb.health.kr/ajax/idfy_info/idfy_info_ajax.asp?drug_name=&drug_print=&match=include&mark_code=&drug_color=&drug_linef=&drug_lineb=&drug_shape=사각형%2C&drug_form=&drug_shape_etc=&inner_search=print&inner_keyword=&strP=20&endP=1&nsearch=nsearch"
response = requests.get(url=url2)
text = response.text
for i in range(1,20):
    s_start = text.find('imgidfy_code')
    s_end = text.find('print_front')
    image = text[s_start+15:s_end-3]
    rnum = text.find('upso_name_kfda')
    print(rnum)
    text = text[rnum+15:]
    print(image)
    url = 'http://www.pharm.or.kr/images/sb_photo/small/'+image
    outfile = image+'.jpg'
    urllib.request.urlretrieve(url+"_s.jpg", outpath+outfile)


from unittest import TestCase
from copy import deepcopy

from followthemoney import model
from followthemoney.dedupe import Match

SAMPLE = {
    "decision": True,
    "canonical": {"id": "can", "schema": "Person", "properties": {"name": ["Tom"]}},
    "entity": {
        "id": "ent",
        "schema": "LegalEntity",
        "properties": {"name": ["Thomas"]},
    },
}

class MatchTestCase(TestCase):
    def test_match_basic(self):
        match = Match(model, deepcopy(SAMPLE))
        assert match.id == "can", match
        assert match.id == match.canonical.id, match
        assert match.entity_id == "ent", match
        assert match.entity_id == match.entity.id, match

        assert match._score is None, match
        assert match.score is not None, match

        sample2 = deepcopy(SAMPLE)
        canon = sample2.pop("canonical")
        sample2["profile_id"] = canon.get("id")
        match = Match(model, sample2)
        assert match.id == "can", match
        assert match.canonical is None, match
        assert match.entity is not None, match
        canon["id"] = "banana"
        match.canonical = model.get_proxy(canon)
        assert match.id == "banana", match
        match.entity = model.get_proxy(canon)
        assert match.entity_id == "banana", match
        assert "banana" in repr(match), repr(match)

    def test_match_to_dict(self):
        match = Match(model, deepcopy(SAMPLE))
        data = match.to_dict()
        assert data["canonical_id"] == "can", data
        assert data["entity_id"] == "ent", data
        assert "score" not in data, data

        assert match.score is not None, match
        data = match.to_dict()
        assert "score" in data, data


from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.core.mail import send_mail
from service.forms import RegisterForm
from django.utils.encoding import force_bytes, force_str
from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode
from service.token import token_generator
from django.conf import settings
from django.template.loader import render_to_string
from django.contrib.sites.shortcuts import get_current_site
from django.views.generic import TemplateView
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.contrib import messages
from django.core.mail import EmailMessage
from django.contrib.auth import get_user_model
# Create your views here.

def SignUpView(request):

    if request.POST:
        email = request.POST['email']
        form = RegisterForm(request.POST)
        if User.objects.filter(email=email).exists():
            messages.error(request, 'Email already registered with an existing account, please use another Email address')
            return redirect('signup')
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()

            mail_subject = "Activate your account."
            message = render_to_string("email/activate_account.html", {
            'user': user.first_name,
            'domain': get_current_site(request).domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': token_generator.make_token(user),
            'protocol': 'https' if request.is_secure() else 'http'
            })

            send_mail(
                mail_subject,
                'Here is the message',
                settings.EMAIL_HOST_USER,
                [user.email],
                html_message=message,
                fail_silently=False
                )
            if send_mail:
                messages.success(request, f"A mail with verification link has been sent to {user.email}")
            else:
                messages.error(request, f'There was an issue sending mail to {user.email}')

            return redirect('index')
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form})

def activateEmail(request, user, to_email):
    mail_subject = "Activate your account."
    message = render_to_string("activate_account.html", {
        'user': user.username,
        'domain': get_current_site(request).domain,
        'uid': urlsafe_base64_encode(force_bytes(user.pk)),
        'token': token_generator.make_token(user),
        'protocol': 'https' if request.is_secure() else 'http'
    })
    email = EmailMessage(mail_subject, message, to=[to_email])
    if email.send:
        messages.success(request, f"A mail with verification link has been sent to {to_email}")
    else:
        messages.error(request, f"There was an issue sending mail to {to_email}")

def activate(request, uidb64, token):
    User = get_user_model()
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)

    except:
        user = None

    if user is not None and token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        messages.success(request, "Thank you for your email confirmation. Now you can login your account.")
        return redirect('login')

    else:
        messages.error(request, "Activation link is invalid")
    return redirect('index')

class CheckEmailView(TemplateView):
    template_name = 'check_email.html'

class SuccessView(TemplateView):
    template_name = 'successful.html'


from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from optparse import OptionParser
import sys, os
from os import chdir
from shutil import copyfile
import requests
from uuid import uuid4
from selenium.common.exceptions import TimeoutException

def query_webpage_statuscode(host,url,timeout):
	try:
		r = requests.head(host+url,timeout=timeout)
		return (r.status_code)
	except Exception as e :
		print (e)
		print ("failed on " + host + url)

def screenshot(host,url,file_name, driver):
	if verbose:
		print ("attempting to screenshot: " + str(url))
	try:
		driver.get(host+url)
		print(file_name)
		driver.save_screenshot(file_name)
		return True
	except TimeoutException:
		if verbose:
			print ("Failed to screenshot: "+ str(e))
		return False

def dirp(host ,URLS, outpath, timeout=10,extension="", verbose=True ,user_agent="Mozilla/5.0 (Windows NT\6.1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/41.0.2228.\0 Safari/537.36"):
	outpath = os.path.join(outpath, "output")
	if not os.path.exists(outpath):
		os.makedirs(outpath)

	print ("Starting on " + host)

	queue = []
	queue.append(host)

	dcap = dict(DesiredCapabilities.PHANTOMJS)
	dcap["phantomjs.page.settings.userAgent"] = user_agent
	dcap["accept_untrusted_certs"] = True
	driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'], desired_capabilities=dcap) # or add to your PATH
	driver.set_window_size(1024, 768) # optional
	driver.set_page_load_timeout(timeout)

	#If these status codes are returned from a HEAD, a screenshot is attempted.
	found_codes = [200,301]
	#if these status codes are returned, it is assumed a directory.
	not_found_codes = [403]

	if not os.path.exists(outpath):
		os.makedirs(outpath)

	while (queue):
		base = queue.pop(0)
		#host = host + base #Take the next root URL

		for url in URLS:
			if (extension is not None):
				url = url + str(extension)
			if verbose:
				print ("Querying " + host + url)
			statuscode = query_webpage_statuscode(host,url,timeout)
			if verbose:
				print ("Status Code: "+ str(statuscode))

			if (statuscode in found_codes):
				print ("found " + url)
				filename = os.path.join("output", str(url + str(uuid4()))  + ".png")
				if verbose:
					if (screenshot(host,url,filename,driver)):
						print ("Successful screenshot: " + str(host) + str(url))
					else:
						print ("Unsuccessful screenshot: "+ str(host) + str(url))
			elif (statuscode in not_found_codes):
				if verbose:
					print ("Found directory: " + str(url))
				queue.append(host+url+"/") #append a found directory

if __name__ == "__main__":
	parser = OptionParser()
	parser.add_option("-f", "--file", action="store", dest="filename",
					  help="Wordlist containing directories", metavar="FILE")
	parser.add_option("-i", "--ip", action="store", dest="host",
					  help="Host to scan. Provided as an IP. Append a base directory for the root folder. i.e. https://192.168.1.1/root/to/scan")
	parser.add_option("-u", '--user-agent', action='store',
					  dest="user_agent", type=str,
					  default="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML,\
							  like Gecko) Chrome/41.0.2228.0 Safari/537.36",
					  help='The user agent used for requests')
	parser.add_option("-t", '--timeout', action='store',
					  dest="timeout", type=int, default=10,
					  help='Number of seconds to try to resolve')
	parser.add_option("-v", action='store_true', dest="verbose",
					  help='Adds some verbosity when running.')
	parser.add_option("-x", action='store', dest="extension",
					  help='extension to append. i.e. .jsp, .html, .aspx')

	(options, args) = parser.parse_args()
	timeout = options.timeout
	verbose = options.verbose
	user_agent = options.user_agent
	extension = options.extension
	if options.filename:
		with open(options.filename, 'r') as inputFile:
			if verbose:
				print ("Using " +options.filename)
			URLS = inputFile.readlines()
			URLS = map(lambda s: s.strip(), URLS)
	else:
		print("No valid wordlist provided.")
		sys.exit()

	if options.host:
		host = options.host
		if not host.startswith("http://") and not host.startswith("https://"):
			print ("Provide a host with a valid HTTP or HTTPS prefix i.e. http:// or https://")
			sys.exit()

	if verbose:
		print("timeout: "+ str(timeout))
		print("verbose: "+ str(verbose))
		print("user_agent: "+ str(user_agent))
		print("extension: "+ str(extension))

	dirp(host, URLS, os.getcwd(), timeout, extension, verbose, user_agent)


#!/usr/bin/python
import MySQLdb
import numpy as np
from sklearn import svm
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import AdaBoostRegressor
import sys
import random
from scipy.stats.stats import pearsonr

# ======load data=======
print('loading data...');
train_X = [];
train_Y = [];
test_X = [];
test_Y = [];
test_ID_list = [];
column_name = [];
Handle_line = 0;

f = open('IS_blending_result.csv', 'r');
for line in f:
	line = line.strip().split(',');
	if(Handle_line == 0):
		column_name = line;
		Handle_line += 1;
		continue;
	line = map(float, line);
	doc_id = int(line[0]);
	score = line[1];
	line = line[2:];

	random_num = random.random();
	if(random_num <= 0.8):
		train_X.append(line);
		train_Y.append(score);
	else:
		test_X.append(line);
		test_Y.append(score);
		test_ID_list.append(doc_id);

print('SVM model prediction');
clf_svm = svm.SVR();
clf_svm.fit(train_X, train_Y);
output_svm = clf_svm.predict(test_X);

print('GradientBoosting model prediction');
clf_GB = GradientBoostingRegressor()
clf_GB.fit(train_X, train_Y);
output_GB = clf_GB.predict(test_X);

print('RandomForest model prediction');
clf_RF = RandomForestRegressor()
clf_RF.fit(train_X, train_Y);
output_RF = clf_RF.predict(test_X);

print('AdaBoost model prediction');
clf_Ada = AdaBoostRegressor()
clf_Ada.fit(train_X, train_Y);
output_Ada = clf_Ada.predict(test_X);

final_output = []
err_0 = 0;
err_1 = 0;
err_2 = 0;
err_3 = 0;
for i in range(len(output_svm)):
	ensemble_output = float(output_svm[i] + output_Ada[i] + output_RF[i] + output_GB[i]) / 4;
	final_output.append(ensemble_output);
	if(abs(ensemble_output - test_Y[i]) <= 0.25):
		err_0 += 1;
	if(abs(ensemble_output - test_Y[i]) <= 1.25):
		err_1 += 1;
	if(abs(ensemble_output - test_Y[i]) <= 2.25):
		err_2 += 1;
	if(abs(ensemble_output - test_Y[i]) <= 3.25):
		err_3 += 1;

print("Precision Exactly right: %lf" % (float(err_0) / len(output_svm)));
print("Precision within 1 point: %lf" % (float(err_1) / len(output_svm)));
print("Precision within 2 point: %lf" % (float(err_2) / len(output_svm)));
print("Precision within 3 point: %lf" % (float(err_3) / len(output_svm)));

# =====counting correlate=====
'''
f = open('IS_correlate.csv', 'w');
for i in range(len(column_name)-2):
	column_data = [];
	for j in range(len(test_ID_list)):
		column_data.append(test_X[j][i]);
	correlate_num = pearsonr(column_data, final_output);
	f.write('%s,%f\n'%(column_name[i+2], correlate_num[0]));
'''


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

# Create your models here.
class Youtuber(models.Model):
    #choice restricting

    crew_choices=(
        ('solo','solo'),
        ('small','small'),
        ('large','large'),
    )

    camera_choices=(
        ('canon','canon'),
        ('fuji','fuji'),
        ('nikon','nikon'),
        ('sony','sony'),
    )

    category_choices=(
        ('education','education'),
        ('comedy','comedy'),
        ('gaming','gaming'),
        ('cooking','cooking'),
    )

    #main fields
    name=models.CharField(max_length=255)
    price=models.IntegerField()
    photo=models.ImageField(upload_to='media/ytubers/%Y/%m/')
    video_url=models.CharField(max_length=255)
    description=RichTextField()
    city=models.CharField(max_length=255)
    age=models.IntegerField()
    crew=models.CharField(choices=crew_choices ,max_length=255,null=True)
    camera=models.CharField(choices=camera_choices ,max_length=255,null=True)
    category=models.CharField(choices=category_choices ,max_length=255,null=True)
    subs_count=models.IntegerField()
    is_featured=models.BooleanField(default=False)
    created_date=models.DateTimeField(default=datetime.now,blank=True)

    def __str__(self):
        return self.name


from django.http import JsonResponse
from drf_yasg2 import openapi
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from drf_yasg2.utils import swagger_auto_schema
from surveybuilder.models import ButtonRowQuestion, ButtonQuestion
from surveybuilder.serializers import ButtonRowQuestionSerializer, ButtonQuestionSerializer

@swagger_auto_schema(operation_summary='Given a ButtonRow entity ID, return the entity and its buttons',
                     methods=['GET'])
@swagger_auto_schema(
    request_body=openapi.Schema(
        title='ButtonQuestion',
        type=openapi.TYPE_OBJECT,
        properties={'buttonRow': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'buttonText': openapi.Schema(type=openapi.TYPE_STRING),
                    'buttonType': openapi.Schema(type=openapi.TYPE_STRING),
                    'buttonIcon': openapi.Schema(type=openapi.TYPE_STRING),
                    'answered': openapi.Schema(type=openapi.TYPE_BOOLEAN),
                    'jumpBlockId': openapi.Schema(type=openapi.TYPE_INTEGER)}
    ),
    operation_summary='Include a new button entity to a ButtonRow entity',
    methods=['POST']
)
@swagger_auto_schema(operation_summary='Delete a button entity from a ButtonRow entity', methods=['DELETE'])
@swagger_auto_schema(
    request_body=openapi.Schema(
        title='ButtonQuestion',
        type=openapi.TYPE_OBJECT,
        properties={'id': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'buttonRow': openapi.Schema(type=openapi.TYPE_INTEGER),
                    'buttonText': openapi.Schema(type=openapi.TYPE_STRING),
                    'buttonType': openapi.Schema(type=openapi.TYPE_STRING),
                    'buttonIcon': openapi.Schema(type=openapi.TYPE_STRING),
                    'answered': openapi.Schema(type=openapi.TYPE_BOOLEAN),
                    'jumpBlockId': openapi.Schema(type=openapi.TYPE_INTEGER)}
    ),
    operation_summary='Update a button entity from a ButtonRow entity',
    methods=['PATCH']
)
@api_view(['GET', 'POST', 'DELETE', 'PATCH'])
def buttonrow_data(request, id):
    """
    get:
    Given a buttonrow entity ID, return the entity and its buttons

    post:
    Include a new button entity to a buttonrow entity

    delete:
    Delete a button entity from a buttonrow entity

    patch:
    Update a button entity from a buttonrow entity
    """
    try:
        buttonrowQuestion = ButtonRowQuestion.objects.get(pk=id)
    except ButtonRowQuestion.DoesNotExist:
        return JsonResponse({'Message': 'The buttonrow can\'t be found.'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        # GET a buttonrow questions information
        buttonrowQuestionSerialized = ButtonRowQuestionSerializer(buttonrowQuestion)
        buttons = ButtonQuestion.objects.filter(buttonRow=id)
        buttonsSerialized = ButtonQuestionSerializer(buttons, many=True)

        # Include all button information to the buttonrow data
        buttonrow_data = buttonrowQuestionSerialized.data
        buttonrow_data['buttons'] = buttonsSerialized.data[:]

        return JsonResponse(buttonrow_data)
    elif request.method == 'POST':
        # POST a button to the buttonrow question

        # parse the button input
        parsed_request = JSONParser().parse(request)
        parsed_request['buttonRow'] = buttonrowQuestion.id
        button_serialized = ButtonQuestionSerializer(data=parsed_request)

        # save the button input
        if button_serialized.is_valid():
            button_serialized.save()
        else:
            return JsonResponse(button_serialized.errors, status=status.HTTP_400_BAD_REQUEST)

        # increment the buttonrow counter
        try:
            buttonrowQuestion.numberButtons += 1
            buttonrowQuestion.save()
            return JsonResponse(button_serialized.data, status=status.HTTP_201_CREATED)
        except:
            return JsonResponse({'Message': 'Couldnt increment buttonrow count.'}, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        # DELETE a button from the button row

        # Expects an object like such {"id": <to-be-deleted>} for the button
        parsed_request = JSONParser().parse(request)
        button_id = parsed_request['id']

        try:
            buttons = ButtonQuestion.objects.get(id=button_id)
            buttons.delete()
            buttonrowQuestion.numberButtons -= 1
            buttonrowQuestion.save()
        except:
            JsonResponse({'Message': 'Couldnt delete the button.'}, status=status.HTTP_400_BAD_REQUEST)

        return JsonResponse({'Message': 'Successfully deleted the button'}, status=status.HTTP_204_NO_CONTENT)

    elif request.method == 'PATCH':
        # UPDATE an existing button within the button row

        # parse the button input
        parsed_request = JSONParser().parse(request)
        parsed_request['buttonRow'] = buttonrowQuestion.id

        # fetch the preexisting object and check incoming request
        button = ButtonQuestion.objects.get(id=parsed_request['id'])
        button_serialized = ButtonQuestionSerializer(button, data=parsed_request, partial=True)

        # save the button input
        if button_serialized.is_valid():
            button_serialized.save()
            return JsonResponse(button_serialized.data)
        else:
            return JsonResponse(button_serialized.errors, status=status.HTTP_400_BAD_REQUEST)