import logging
import discord.ui
from discord import app_commands
from discord.ext import commands
from discord import Embed, Colour, Interaction
from extensions.uiactions import CreditsView, HelpView, VoteButton, AdminRoleView
from extensions.helpers import get_platform, claim_credits
from extensions.constants import Analytics
from extensions.embeds import help_overview_embed, vote_embed, get_credits_embed
from core.Server import Server

# Set up logging
logger = logging.getLogger(__name__)

class ServerSettings(commands.Cog):
    """A cog for server settings."""

    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name="adminroles", description="If admin roles are set, only users with admin roles can modify Dis.AI chatbots.")
    @app_commands.guild_only()
    async def adminroles(self, interaction: Interaction) -> None:
        """Handle admin roles command."""
        try:
            if not interaction.guild:
                await self._send_error_message(interaction, "Cannot perform this action in a DM")
                return
            elif not interaction.user.guild_permissions.administrator:
                await self._send_error_message(interaction, "Must have administrator permissions to use this")
                return
            platform = await get_platform(self.bot.platforms, interaction, Analytics.ADMINROLES.value)
            await interaction.response.send_message(embed=Embed(title="Select Option", description="", colour=Colour.blue()), view=AdminRoleView(platform), ephemeral=True)
        except Exception as error:
            logger.error(f"admin roles err: {error}")

    @app_commands.command(name="credits", description="View and purchase Dis.AI Credits")
    async def credits(self, interaction: Interaction) -> None:
        """Handle credits command."""
        try:
            platform = await get_platform(self.bot.platforms, interaction, Analytics.CREDITS.value)
            portfolio_str = self._get_portfolio_str(platform)
            embed = await get_credits_embed(portfolio_str)
            await interaction.response.send_message(embed=embed, view=CreditsView(platform), ephemeral=True)
        except Exception as error:
            logger.error(f"/credits err: {error}")

    @app_commands.command(name="help", description="Show the help page")
    async def help(self, interaction: Interaction) -> None:
        """Handle help command."""
        try:
            await interaction.response.send_message(embed=help_overview_embed, view=HelpView(), ephemeral=True)
        except Exception as error:
            logger.error(f"/help err: {error}")

    @app_commands.command(name="vote", description="Vote for Dis.AI to earn free credits")
    async def vote(self, interaction: Interaction) -> None:
        """Handle vote command."""
        try:
            platform = await get_platform(self.bot.platforms, interaction, Analytics.VOTECOMMAND.value)
            view = discord.ui.View()
            view.add_item(VoteButton(platform))
            await interaction.response.send_message(embed=vote_embed, view=view, ephemeral=True)
        except Exception as error:
            logger.error(f"/vote err: {error}")

    @app_commands.command(name="claim", description="Claim free Dis.AI credits")
    async def claim(self, interaction: Interaction) -> None:
        """Handle claim command."""
        await claim_credits(interaction, self.bot.platforms)

    async def _send_error_message(self, interaction: Interaction, description: str) -> None:
        """Send an error message."""
        await interaction.response.send_message(embed=Embed(title="Error", description=description, color=Colour.red()))

    def _get_portfolio_str(self, platform) -> str:
        """Get portfolio string."""
        if isinstance(platform, Server):
            return f"This server ({platform.name}) has **{platform.credits} credits.**"
        else:
            return f"This DM channel has **{platform.credits} credits.**"

async def setup(bot):
    await bot.add_cog(ServerSettings(bot))


# xyz
import sys
n = 0
content = ''
if len(sys.argv) > 1:
    n = int(sys.argv[1])
if len(sys.argv) > 2:
    content = sys.argv[2]

def append(l: list, s: str, n: int):
    _d = 1
    for i, v in enumerate(l):
        if v:
            if len(l[i]) < n:
                l[i] += s
        elif _d:
            l[i] += s
            _d = 0
        else:
            break
    print(l)

def print_xyz(n: int):
    list_all = ['']*len(content)
    for i in content:
        if i in "xyz":
            append(list_all, i, n)
    print(content)
    print([i for i in list_all if len(i) == n])

if __name__ == "__main__":
    print_xyz(n)


import pandas as pd
from typing import List, Dict

from .variant import Variant

ACCEPTABLE_GENOTYPES = {"heterozygous", "homozygous", "hemizygous"}

class VariantColumnMapper:
    """Column mapper for the variants identified in individuals

    To use this mapper, first create a dictionary with all variants in the cohort using the
    VariantValidator (for HGVS) and the StructuralVariant classes. The key to the variant is
    the cell contents of the column with variant information in the original table. The Values
    are the Variant objects (implemented as HgvsVariant or StructuralVariant). This mapper will
    split cells that contain multiple variants if needed and also will add genotype information.

    :param variant_d: Dictionary with all variants found in the column
    :type variant_d: Dict[str,Variant]
    :param variant_column_name: name of the variant column in the original table
    :type variant_column_name: str
    :param genotype_column_name: name of the genotype column in the original table, optional
    :type genotype_column_name: str
    :param delimiter: symbol used to separate variants if more than one variant is provided, optional
    :type delimiter: str
    """
    def __init__(self,
                 variant_d,
                 variant_column_name,
                 genotype_column_name=None,
                 default_genotype=None,
                 delimiter=None) -> None:

        if default_genotype is not None and default_genotype not in ACCEPTABLE_GENOTYPES:
            raise ValueError(f"Did not recognize default genotype {default_genotype}")
        if not isinstance(variant_d, dict):
            raise ValueError(f"Argument variant_d must be a dictionary but was {type(variant_d)}")
        self._variant_d = variant_d
        self._default_genotype = default_genotype
        self._variant_column_name = variant_column_name
        self._genotype_column_name = genotype_column_name
        self._delimiter = delimiter

    def _get_genotype(self, genotype_contents):
        """
        Get a genotype string

        get the genotype from the argument (which comes from the genotype column if available) or from the
        default genotype.
        :returns: one of "heterozygous", "homozygous", "hemizygous", None
        """
        if genotype_contents is not None and genotype_contents.lower() in ACCEPTABLE_GENOTYPES:
            return genotype_contents.lower()
        else:
            return self._default_genotype

    def map_cell(self, cell_contents, genotype_contents=None, delimiter=None) -> List[Variant]:
        """
        Map the contents of a variant cell (and optionally a genotype cell).

        If the delimiter is not None, search for the delimiter and split the cell into two variants
        :param cell_contents: contents of the original table cell representing the variant string
        :type cell_contents: str
        :param genotype_contents: contents of the original table cell representing the genotype (allelic status), optional
        :type genotype_contents: str
        :param delimiter: string or character that splits the cell contents into multiple entries, e.g., ";", optional
        :type delimiter: str
        """
        if delimiter is None:
            delimiter = self._delimiter
        if delimiter is not None:
            items = [x.strip() for x in cell_contents.split(delimiter)]
        else:
            items = [cell_contents]
        variant_interpretation_list = []
        for item in items:
            if item in self._variant_d:
                variant: Variant = self._variant_d.get(item)
                gt = self._get_genotype(genotype_contents)
                if gt is not None:
                    variant.set_genotype(gt)
                interpretation = variant.to_ga4gh_variant_interpretation()
                variant_interpretation_list.append(interpretation)
            else:
                raise ValueError(f"Did not recognize variant string \"{item}\"")

        return variant_interpretation_list

    def preview_column(self, column) -> pd.DataFrame:
        if not isinstance(column, pd.Series):
            raise ValueError("column argument must be pandas Series, but was {type(column)}")
        dlist = []
        for _, value in column.items():
            variant_interpretation_list = self.map_cell(str(value))
            if len(variant_interpretation_list) == 0:
                dlist.append({"variant": "n/a"})
            else:
                result_strings = []
                for v in variant_interpretation_list:
                    result_strings.append(v.__str__())
                dlist.append({"variant": ": ".join(result_strings)})
        return pd.DataFrame(dlist)

    def get_variant_column_name(self):
        return self._variant_column_name

    def get_genotype_colname(self):
        return self._genotype_column_name


import csv

import matplotlib as matplotlib
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from collections import defaultdict
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
from IPython.display import Image
from sklearn.tree import export_graphviz
disease_list=[]
def return_list(disease):
    disease_list=[]
    match=disease.replace('^','_').split('_')
    ctr=1
    for group in match:
        if ctr%2==0:
            disease_list.append(group)
        ctr=ctr+1
    return disease_list
with open("dataset_uncleaned.csv") as csvfile:
    reader = csv.reader(csvfile)
    disease=""
    weight = 0
    disease_list = []
    dict_wt = {}
    dict_=defaultdict(list)
    for row in reader:

        if row[0]!="\xc2\xa0" and row[0]!="":
            disease = row[0]
            disease_list = return_list(disease)
            weight = row[1]

        if row[2]!="\xc2\xa0" and row[2]!="":
            symptom_list = return_list(row[2])

            for d in disease_list:
                for s in symptom_list:
                    dict_[d].append(s)
                dict_wt[d] = weight
with open("dataset_clean.csv", "w") as csvfile:
    writer = csv.writer(csvfile)
    for key,values in dict_.items():
        for v in values:
            #key = str.encode(key)
            key = str.encode(key).decode('utf-8')
            #.strip()
            #v = v.encode('utf-8').strip()
            #v = str.encode(v)
            writer.writerow([key,v,dict_wt[key]])
if __name__ == '__main__':
    columns = ['Source','Target','Weight']
    data = pd.read_csv("dataset_clean.csv", names=columns, encoding ="ISO-8859-1")
    data.head()
    print(data.head())
    data.to_csv("diseaseData/dataset_clean.csv",index=False)
    slist = []
    dlist = []
    with open("nodetable.csv", "w") as csvfile:
        writer = csv.writer(csvfile)

        for key, values in dict_.items():
            for v in values:
                if v not in slist:
                    writer.writerow([v, v, "symptom"])
                    slist.append(v)
            if key not in dlist:
                writer.writerow([key, key, "disease"])
                dlist.append(key)

    nt_columns = ['Id', 'Label', 'Attribute']
    nt_data = pd.read_csv("nodetable.csv", names=nt_columns, encoding="ISO-8859-1", )
    nt_data.head()
    print(nt_data.head())
    nt_data.to_csv("diseaseData/nodetable.csv", index=False)
    data = pd.read_csv("dataset_clean.csv", encoding="ISO-8859-1")
    data.head()
    print(len(data['Source'].unique()))
    print(len(data['Target'].unique()))
    df = pd.DataFrame(data)
    df_1 = pd.get_dummies(df.Target)
    df_1.head()
    print(df_1.head())
    print(df.head())
    df_s = df['Source']
    df_pivoted = pd.concat([df_s, df_1], axis=1)
    df_pivoted.drop_duplicates(keep='first', inplace=True)
    print(df_pivoted[:5])
    print(len(df_pivoted))
    cols = df_pivoted.columns
    cols = cols[1:]
    df_pivoted = df_pivoted.groupby('Source').sum()
    df_pivoted = df_pivoted.reset_index()
    print(df_pivoted[:5])
    print(len(df_pivoted))
    df_pivoted.to_csv("diseaseData/df_pivoted.csv")
    x = df_pivoted[cols]
    y = df_pivoted['Source']
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
    mnb = MultinomialNB()
    mnb = mnb.fit(x_train, y_train)
    print(mnb.score(x_test, y_test))
    mnb_tot = MultinomialNB()
    mnb_tot = mnb_tot.fit(x, y)
    print(mnb_tot.score(x, y))
    disease_pred = mnb_tot.predict(x)
    disease_real = y.values
    for i in range(0, len(disease_real)):
        if disease_pred[i] != disease_real[i]:
            print('Pred: {0} Actual:{1}'.format(disease_pred[i], disease_real[i]))

    print("DecisionTree")
    dt = DecisionTreeClassifier()
    clf_dt = dt.fit(x, y)
    print("Acurracy: ", clf_dt.score(x, y))
    Image(filename='tree.png')
    export_graphviz(dt,
                    out_file='diseaseData/tree.dot',
                    feature_names=cols)

    data = pd.read_csv("Training.csv")
    print(data.head())
    data = pd.read_csv("Training.csv")
    print(data.columns)
    print(len(data.columns))
    print(len(data['prognosis'].unique()))
    df = pd.DataFrame(data)
    print(df.head())
    print(len(df))
    cols = df.columns
    cols = cols[:-1]
    print(cols)
    print(len(cols))
    x = df[cols]
    y = df['prognosis']
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=42)
    print("DecisionTree")
    dt = DecisionTreeClassifier()
    clf_dt = dt.fit(x_train, y_train)
    print("Acurracy: ", clf_dt.score(x_test, y_test))

    print("cross result========")
    scores = cross_val_score(dt, x_test, y_test, cv=3)
    print(scores)
    print(scores.mean())
    export_graphviz(dt,
                    out_file='diseaseData/tree.dot',
                    feature_names=cols)
    dt.__getstate__()
    importances = dt.feature_importances_
    indices = np.argsort(importances)[::-1]

    # Print the feature ranking
    print("Feature ranking:")
    features = cols
    for f in range(5):
        print("%d. feature %d - %s (%f)" % (f + 1, indices[f], features[indices[f]], importances[indices[f]]))
    export_graphviz(dt,
                    out_file='diseaseData/tree-top5.dot',
                    feature_names=cols,
                    max_depth=5
                    )
    Image(filename='tree-top5.png')
    feature_dict = {}
    for i, f in enumerate(features):
        feature_dict[f] = i
    print(feature_dict['redness_of_eyes'])
    sample_x = [i / 52 if i == 52 else i * 0 for i in range(len(features))]
    print(len(sample_x))
    sample_x = np.array(sample_x).reshape(1, len(sample_x))
    print(dt.predict(sample_x))
    print(dt.predict_proba(sample_x))


import openpyxl
from openpyxl.styles import Font
from openpyxl.utils import get_column_letter

filepath=input('Enter the absolute path to the folder where the files are saved:')

files=input('Enter the file names to insert into spreadsheet :') #seperated by space
filesList = files.split()

wb = openpyxl.Workbook()
sheet = wb.active

columnNum = 1
for file in filesList:

    lines = open(filepath + '\\' + file).readlines()

    toBold = Font(bold=True)
    sheet.cell(row=1, column=columnNum).value = file
    sheet.cell(row=1, column=columnNum).font = toBold

    longest = 0
    row_num = 2
    for line in lines:
        line = line.strip()

        if len(line) > longest:
            longest = len(line)

        sheet.cell(row=row_num, column=columnNum).value = line
        row_num += 1

    column_letter = get_column_letter(columnNum)
    sheet.column_dimensions[column_letter].width = longest
    column_num += 1

wb.save(filepath + '\\text2sheet'+file)
print('Spreadsheet saved with text2sheet prefix in the same directory')


from init import *
import math
from bokeh.layouts import gridplot
from bokeh.plotting import figure, show, output_file
from bokeh.models import Legend
from bokeh.models import Range1d
import numpy

rowcount = []
rowsum = 0
dates = []

for year, data in pd_data.split('year').items():
  for month, month_data in data.split('month').items():
    rowsum += month_data.shape[0]
    rowcount.append(rowsum)
    dates.append((month, year))

def datetime(dates):
    format = [str(x[1])+'-'+add_zero(x[0])+'-01' for x in dates]
    return np.array(format, dtype=np.datetime64)

def plot(plot, legend_names):
    plot.grid.grid_line_alpha=0.3
    plot.xaxis.axis_label = 'Datum'
    plot.yaxis.axis_label = 'Aantal rijen'
    legend = Legend(items=legend_names, location=(0, -30))
    plot.add_layout(legend, 'right')

    show(gridplot([[plot]], sizing_mode='stretch_both'))  # open a browser

def add_zero(x):
    if x < 10:
        return '0'+str(x)
    else:
        return str(x)

def add_to_plot(plot, name, dates, values):
    return plot.line(datetime(dates), values, color='#1982C4', line_width=2)

plot1 = figure(x_axis_type="datetime", title='Cumulatieve rijen door de jaren heen', sizing_mode='stretch_both')
legend = []
# legend.append(('Aantal',[add_to_plot(plot1,'rowcount',dates,rowcount)]))
add_to_plot(plot1,'rowcount',dates,rowcount)
plot(plot1,legend)


class Solution:
    def lengthOfLongestSubstring(self, s):
        """
            find the length of the longest substring w/o repeating chars
            :type s: str
            :rtype: int/str
        """
        if not s or len(s)<1: return 0

        # store the last location of the char in string s
        hashmap = {}
        # left pointer, keep two pointers which define the max substring
        l=0
        maxLen=0
        maxLenStr=''

        # move the right pointer to scan the string, meanwhile update the hashmap
        for r in range(len(s)):
            # if the current char is already in the hashmap
            # and the last location of this char is not to the left of the left pointer
            # we move the left pointer to the right of the last location of this char
            # since if the the last location of this char is to the left of the left pointer,
            # it won't affect the unquieness of the char in current max-length string
            if s[r] in hashmap and hashmap[s[r]]>=l:
                l=hashmap[s[r]]+1
            else:
                if r-l+1>maxLen:
                    maxLen=r-l+1
                    maxLenStr=s[l:r+1]

            hashmap[s[r]]=r

        # return maxLen
        return maxLenStr

# test
sol=Solution()
s="leetcodingforfun"
print("The longest substring w/o repeating characters of the string '%s' is: '%s'" % (s,sol.lengthOfLongestSubstring(s)))


import sys

def main():
    input = sys.stdin.readline
    N = int(input())
    A = list(map(int, input().split()))
    ans = 10**5
    for i in range(1, N):
        s1 = sum(A[:i])
        s2 = sum(A[i:])
        ans = min(ans, abs(s1 - s2))

    return ans

if __name__ == '__main__':
    print(main())


from django.db import models
from django.contrib.auth.models import AbstractUser
# from django.contrib.auth import get_user_model
# User = get_user_model()
# Create your models here.

status = [("Active", "Active"), ("Inactive", "Inactive"), ("Delete", "Delete")]
gender = [('Male', 'Male'), ('Female', 'Female'), ('Others', 'Others')]

class User(AbstractUser):

    email = models.EmailField( null=True)
    phone_no =models.CharField(max_length= 10, null=True)
    city = models.CharField(max_length=20, null=True)
    country = models.CharField(max_length=20, null = True)
    image = models.ImageField( upload_to='profile/')
    gender = models.CharField(max_length=10, choices=gender, default='Male')
    dob = models.DateField(null=True, blank=True)
    address = models.CharField(null=True, blank=True)
    status = models.CharField(max_length=20, choices=status, default='Active')
    timestamp = models.DateTimeField(auto_now_add=True)
    utimestamp = models.DateTimeField(auto_now=True)
    track = models.TextField(blank=True, editable=False)
    utrack = models.TextField(blank=True, editable=False)

    def __str__(self):
        return self.email

# class Category(models.Model):
#     title = models.CharField(max_length=40)
#     icon = models.ImageField(null=True, blank=True, upload_to='icon/')
#     description = models.TextField(null=True, blank=True)
#     PENDING = 0
#     DONE = 1
#     STATUS_CHOICES = ((PENDING, 'Pending'),(DONE, 'Done'),)
#     status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Active')
#     timestamp = models.DateTimeField(auto_now_add=True)
#     utimestamp = models.DateTimeField(auto_now=True)
#     track = models.TextField(blank=True, editable=False)
#     utrack = models.TextField(blank=True, editable=False)


# 쇠막대기는 자신보다 긴 쇠막대기 위에만 놓일 수 있다.
# - 쇠막대기를 다른 쇠막대기 위에 놓는 경우 완전히 포함되도록 놓되, 끝점은 겹치지 않도록 놓는다.
# 각 쇠막대기를 자르는 레이저는 적어도 하나 존재한다.
# 레이저는 어떤 쇠막대기의 양 끝점과도 겹치지 않는다.

# 시작 괄호 를 만날때 마다 막대기의 길이를 가늠한다다
import sys
input = sys.stdin.readline
stack = []
count = 0
stick = input() # 쇠 막대기
for i in range(len(stick)):
    if stick[i] == '(': # 시작 괄호라면 스택에 삽입하여 길이를 늘려준
        stack.append('(')
    else: # 닫는 괄호라면
        if stick[i-1]=='(': # 이전 괄호가 여는 괄호라면 한쌍이 만나 레이저가 된다
            stack.pop() # 한 쌍을 이루었기에 ( 를 꺼내준다
            count += len(stack)
        else: # 이전 괄호가 닫는 괄호라면
            stack.pop() # 막대가 있다는 뜻이므로 길이 +1 을 해준다
            count += 1
print(count)


import cv2
import sys
import os

class PackageProjectUtil:
    @staticmethod
    def project_root_path(project_name=None, print_log=True):
        """
        获取当前项目根路径
        :param project_name: 项目名称
        :param print_log: 是否打印日志信息
        :return: 指定项目的根路径
        """
        p_name = 'Yolov5_Efficient' if project_name is None else project_name
        project_path = os.path.abspath(os.path.dirname(__file__))
        # Windows
        if project_path.find('\\') != -1: separator = '\\'
        # Mac、Linux、Unix
        if project_path.find('/') != -1: separator = '/'

        root_path = project_path[:project_path.find(f'{p_name}{separator}') + len(f'{p_name}{separator}')]
        if print_log: print(f'当前项目名称：{p_name}\r\n当前项目根路径：{root_path}')
        return root_path

# 将当前项目目录添加至Python编译器路径(兼容python命令行运行方式)
sys.path.append(PackageProjectUtil.project_root_path())
# 当前目录
rpath = sys.path[0]

from yolov5_master.train import train_main, train_parse_opt
from yolov5_master.detect import detect_main, detect_parse_opt

def train_(data_path, model_cfg_path, models_name='yolov5s'):
    # 初始化参数列表
    t_opt = train_parse_opt()
    """
    重设自定义参数,进行模型训练
    Usage-命令行使用方式:
    $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640
    Usage-IDE使用方式：直接在下面对应位置进行修改
    """
    # 数据集配置文件
    t_opt.data = data_path
    # 模型配置文件
    t_opt.cfg = model_cfg_path

    # 数据集配置文件
    # t_opt.data = rpath + '/data/' + 'custom/' + 'voc_' + object_name + '.yaml'
    # # 模型配置文件
    # t_opt.cfg = rpath + '/models/custom/' + models_name + '_' + object_name + '.yaml'
    # 预训练权重
    # weights/yolov5l.pt,yolov5l6.pt,yolov5m.pt,yolov5m6.pt,yolov5s6.pt,yolov5x.pt,yolov5x6.pt
    t_opt.weights = rpath + '/weights/' + models_name + '.pt'
    # 设置单次训练所选取的样本数
    t_opt.batch_size = 1
    # 设置训练样本训练的迭代次数
    t_opt.epochs = 300
    # 设置线程数
    t_opt.workers = 4
    # 训练结果的文件名称
    t_opt.name = models_name + '_' + object_name
    # 是否单分类
    t_opt.single_cls = False

    """开始训练"""
    train_main(t_opt)

def detect_(object_name, models_name='yolov5s'):
    # 初始化参数列表
    d_opt = detect_parse_opt()
    """
    重设自定义参数,进行预测推理
    Usage-命令行使用方式:
    $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640
    Usage-IDE使用方式：直接在下面对应位置进行修改
    """
    # 图像/图像集合/视频的源路径,内部自动文件类型进行判断
    d_opt.source = '/media/hxzh02/TT/工装数据/行人检测视频.mp4'
    # 设置进行预测推理使用的权重模型文件
    # d_opt.weights = rpath + '/runs/train/' + models_name + '_' + object_name + '/weights/best.pt'
    d_opt.weights = '/media/hxzh02/SB@home/hxzh/MyGithub/TrainNetHub/YOLO/yolov5_master/runs/train/yolov5s_workclothes7/weights/best.pt'
    # 设置是否需要预览
    d_opt.view_img = False
    # 置信度设置
    d_opt.conf_thres = 0.5
    # 边界框线条粗细
    d_opt.line_thickness = 4

    """开始预测推理"""
    detect_main(d_opt)

if __name__ == '__main__':
    # 设置训练任务/生成模型名称
    object_list = [
        'tower', 'foreignbody',
        'smoke', 'insulator',
        'helmet', 'firesmoke',
        'plane_all', 'tower_only',
        'tower_head', 'towerlean'
    ]

    # object_name = 'tower_body'
    # object_name = 'towerlean'
    # object_name = 'coco128_panet'
    # object_name = 'towerbody_base'
    object_name = 'coco128'
    # 模型选择
    models_list = [
        'yolov5n', 'yolov5n6',
        'yolov5s', 'yolov5s6',
        'yolov5m', 'yolov5m6',
        'yolov5l', 'yolov5m6',
        'yolov5x', 'yolov5x6',
    ]
    models_name = models_list[2]

    # 模型训练
    data_path = '/media/hxzh02/SB@home/hxzh/MyGithub/Yolov5_Efficient/yolov5_master/data/coco128.yaml'

    model_cfg_path = '/media/hxzh02/SB@home/hxzh/MyGithub/Yolov5_Efficient/yolov5_master/models/yolov5s.yaml'
    train_(data_path=data_path, model_cfg_path=model_cfg_path, models_name='yolov5s')

    # 模型预测
    # detect_(object_name)


from itertools import product

from django.urls import path
from .views import *

app_name = 'main'

urlpatterns = [
   path('', index, name='index'),
   path('login/', LoginView.as_view(), name='login'),
   path('logout/', LogoutView.as_view(), name='logout'),
   path('accounts/profile/', profile, name='profile'),
   path('about/', about, name='about'),
   path('contacts/', contacts, name='contacts'),
   path('product/', product, name='product'),
]


"""
Test the 'commands.apply' module.
"""

# module under test
from rcmpy import PKG_NAME
from rcmpy.entry import main as rcmpy_main

# internal
from tests.resources import file_removed, scenario

def test_apply_command_empty():
    """Test the 'apply' command against the 'empty' scenario."""

    with scenario("empty"):
        assert rcmpy_main([PKG_NAME, "apply"]) != 0

def test_apply_command_simple():
    """Test the 'apply' command against the 'simple' scenario."""

    with scenario("simple", variant="test") as root:
        assert rcmpy_main([PKG_NAME, "apply"]) == 0

        templates = root.joinpath("templates")

        # Remove the 'test.txt' template in the variant directory
        # (temporarily).
        with file_removed(templates.joinpath("test", "test.txt")):
            assert rcmpy_main([PKG_NAME, "apply"]) == 0

            # Remove the 'test.txt' template in the common directory
            # (temporarily).
            with file_removed(templates.joinpath("common", "test.txt")):
                assert rcmpy_main([PKG_NAME, "apply"]) != 0

            # Run again with the common template restored.
            assert rcmpy_main([PKG_NAME, "apply"]) == 0

        # Run again with the variant template restored.
        assert rcmpy_main([PKG_NAME, "apply"]) == 0

def test_apply_command_missing_template():
    """Test the 'apply' command against the 'missing_template' scenario."""

    with scenario("missing_template"):
        assert rcmpy_main([PKG_NAME, "apply"]) != 0


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

m = 100

means = [
    0.5*np.ones(m),
    0.5*np.linspace(-1, 1, m),
    0.5*np.linspace(-1, 1, m)**2,
    0.2*np.sin(np.linspace(-7, 7, m)),
]

pca = [
    np.ones(m),
    np.linspace(-1, 1, m),
    np.linspace(-1, 1, m)**2,
    np.linspace(-1, 1, m)**2 - 0.5,
    np.sin(np.linspace(-7, 7, m)),
]

for j in range(len(pca)):
    pca[j] /= np.sqrt(np.sum(pca[j]**2))

pdf = PdfPages("pca.pdf")

for j in range(len(means)):
    for k in range(len(pca)):

        plt.clf()
        plt.axes([0.1, 0.1, 0.7, 0.8])
        plt.grid(True)
        plt.plot(means[j], '-', color='orange', label='Mean')
        plt.plot(pca[k], '-', color='purple', label='Loadings')
        ha, lb = plt.gca().get_legend_handles_labels()
        leg = plt.figlegend(ha, lb, "center right")
        leg.draw_frame(False)
        plt.ylim(-1, 1)
        pdf.savefig()

        plt.clf()
        plt.grid(True)
        plt.plot(means[j], '-', lw=4, color='orange')
        for i in range(10):
            u = np.random.uniform(-1, 1)
            plt.plot(means[j] + u*pca[k], '-', color='grey')
        pdf.savefig()

pdf.close()

import os
os.system("cp pca.pdf ~kshedden")


# This script checks module.json for:
#
# 1. all commits references exist in the linear history of the current branch
# 2. there are no duplicate numeric versions for the same module ID, say `go-1.19-v1-20230412-9uegy7e`
#    and `go-1.19-v1-20230501-cceo023`

import subprocess
import os
import json

module_registry_file = 'modules.json'

def commit_exists(commit):
  try:
    output = subprocess.check_output(['git', 'show', '-s', '--format=format:%H', commit])
    return str(output, 'UTF-8') == commit
  except:
    return False

def get_commits(modules):
  commits = set()
  for entry in modules.values():
    commits.add(entry['commit'])
  return commits

def check_commits_exist(modules):
  for commit in get_commits(modules):
    assert commit_exists(commit), 'Commit %s does not exist!' % commit

def get_modules():
  if not os.path.isfile(module_registry_file):
    return {}
  f = open(module_registry_file, 'r')
  modules = json.load(f)
  f.close()
  return modules

def check_no_duplicate_numeric_versions(modules):
  uniques = {}
  for key in modules.keys():
    module_id, tag = key.split(':')
    version, _, _ = tag.split('-')
    short_key = "%s:%s" % (module_id, version)
    if short_key in uniques:
      raise Exception("%s has duplicate numeric versions: %s and %s" % (module_id, key, uniques[short_key]))
    uniques[short_key] = key

def main():
  modules = get_modules()
  check_commits_exist(modules)
  check_no_duplicate_numeric_versions(modules)

if __name__ == '__main__':
  main()


import argparse
import torch
from tqdm import tqdm
import dataloader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch
from parse_config import ConfigParser
import torch.nn.functional as F

from model import handDetector

import cv2

import torchvision
from torchvision.transforms._transforms_video import (
    CenterCropVideo,
    NormalizeVideo
)

from torchvision.transforms import (
    Normalize,
    Resize,
    RandomCrop,
    RandomHorizontalFlip,
    RandomRotation
)
from pytorchvideo.transforms import (
    # Normalize,
    ShortSideScale,
    UniformCropVideo,
    RandomShortSideScale,
    ShortSideScale
)

def main(config):
    hand_det = handDetector()

    image_transforms = torchvision.transforms.Compose([
        Normalize((0.45, 0.45, 0.45), (0.225, 0.225, 0.225)),
        ShortSideScale(320),
        CenterCropVideo(244)

    ])
    hand_transforms = torchvision.transforms.Compose([
        Normalize((0.45, 0.45, 0.45), (0.225, 0.225, 0.225)),
        Resize([244,244]),

    ])

    pre_transforms = torchvision.transforms.Compose([
        Resize([480,640]),

    ])

    logger = config.get_logger('test')

    # setup data_loader instances
    data_loader = getattr(module_data, config['data_loader']['type'])(
        csv_dir=config['data_loader']['args']['csv_dir'],
        data_dir=config['data_loader']['args']['data_dir'],
        batch_size=config['data_loader']['args']['batch_size'],
        shuffle=config['data_loader']['args']['shuffle'],
        validation_split=config['data_loader']['args']['validation_split'],
        training=False,
        num_workers=config['data_loader']['args']['num_workers'],
        num_frames=config['data_loader']['args']['num_frames'],
        categories=config['data_loader']['args']['categories']

    )
    valid_data_loader = data_loader.split_validation()

    # build model architecture
    model_image = config.init_obj('arch_image', module_arch)
    model_hand = config.init_obj('arch_hand', module_arch)

    logger.info(model_image)
    logger.info(model_hand)

    # get function handles of loss and metrics
    loss_fn = getattr(module_loss, config['loss'])
    metric_fns = [getattr(module_metric, met) for met in config['metrics']]

    #IMAGE MODEL######################################################
    logger.info('Loading checkpoint: {} ...'.format(config.resume))
    checkpoint = torch.load(config.resume)
    state_dict = checkpoint['state_dict']
    # REMOVE
    from collections import OrderedDict
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = 'module.' + k  # remove `module.`
        new_state_dict[name] = v

    if config['n_gpu'] > 1:
        model_image = torch.nn.DataParallel(model_image)
    model_image.load_state_dict(new_state_dict)

    # prepare model for testing
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(device)
    model_image = model_image.to(device)
    model_image.eval()
    #################################################################

    #HAND MODEL######################################################
    checkpoint = torch.load("results/res50/models/model_best.pth")
    state_dict = checkpoint['state_dict']
    # REMOVE
    from collections import OrderedDict
    new_state_dict = OrderedDict()
    for k, v in state_dict.items():
        name = 'module.' + k  # remove `module.`
        new_state_dict[name] = v

    if config['n_gpu'] > 1:
        model_hand = torch.nn.DataParallel(model_hand)
    model_hand.load_state_dict(new_state_dict)

    # prepare model for testing
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print(device)
    model_hand = model_hand.to(device)
    model_hand.eval()
    #################################################################

    total_loss = 0.0
    total_metrics = torch.zeros(len(metric_fns))
    num_classes = config['arch']['args']['num_categories']
    conf_mat = torch.zeros(num_classes, num_classes)
    num_imgs = 0
    accuracy = 0.0
    accuracy_max = 0.0
    pred_hand_imgs = 0
    pred_big_imgs = 0
    with torch.no_grad():
        for i, (data, target) in enumerate(tqdm(valid_data_loader)):
            target = target.type(torch.LongTensor)
            roll_batch = torch.zeros(data.shape[0], num_classes)
            for j in range(data.shape[0]):
                imgs = data[j, :, :, :, :].permute(1, 0, 2, 3)
                tt = target[j]
                output = torch.zeros(imgs.shape[0], num_classes)
                i = 0
                for im in imgs:
                    im_p = pre_transforms(im)
                    im_p = im_p.permute(1, 2, 0).numpy()*255
                    im_p = cv2.cvtColor(im_p, cv2.COLOR_RGB2BGR)
                    pr_im = hand_det.predict_hands(im_p)
                    if (pr_im is not None):
                        print("predict with hands")
                        pred_hand_imgs += 1
                        pr_hand = cv2.cvtColor(pr_im, cv2.COLOR_BGR2RGB)
                        pr_hand = torch.from_numpy(pr_hand)/255.0
                        pr_hand = pr_hand.permute(2,0,1)
                        pr_hand = torch.unsqueeze(pr_hand, 0)
                        pr_hand = hand_transforms(pr_hand)
                        pr_hand = pr_hand.to(device)
                        out = model_hand(pr_hand)
                    else:
                        print("predict with image")
                        pred_big_imgs += 1
                        im = torch.unsqueeze(im, 0)
                        im = image_transforms(im)
                        im = im.to(device)
                        out = model_image(im)
                    output[i] = out
                    i = i+1

                # Average prediction
                roll_avg = torch.mean(output, 0)
                roll_batch[j] = roll_avg

                # Max prediction
                roll_max = torch.argmax(output, 1)
                max_pred = torch.mode(roll_max).values
                if (tt == max_pred):
                    accuracy_max += 1

                # Individual prediction
                num_imgs = num_imgs + 1
                tt = tt.repeat(imgs.shape[0])
                accuracy += module_metric.accuracy(output, tt)

                #probs = F.softmax(output, dim= 1)
                #probs_avg = F.softmax(roll_avg)
                #print("Output: ", output)
                #print("Probs: ", probs)
                #print("Probs avg: ", probs_avg)
                #print("Roll avg: ", roll_avg)
                #print("Target: ", tt)

            # computing loss, metrics on test set
            loss = loss_fn(roll_batch, target)
            batch_size = data.shape[0]
            total_loss += loss.item() * batch_size
            for i, metric in enumerate(metric_fns):
                total_metrics[i] += metric(roll_batch, target) * batch_size
            module_metric.conf_mat(roll_batch, target, conf_mat)

    n_samples = len(valid_data_loader.sampler)
    log = {'loss': total_loss / n_samples}
    log.update({
        met.__name__: total_metrics[i].item() / n_samples for i, met in enumerate(metric_fns)
    })
    log.update({
        "Individual accuracy": accuracy / num_imgs,
        "Rolling Max accuracy": accuracy_max / num_imgs,
        "Hand found percentage": pred_hand_imgs / (pred_hand_imgs + pred_big_imgs),
        "Hand not found": pred_big_imgs / (pred_hand_imgs + pred_big_imgs)

    })
    precision = torch.nan_to_num(conf_mat.diag() / conf_mat.sum(0))
    recall = torch.nan_to_num(conf_mat.diag() / conf_mat.sum(1))
    f1 = module_metric.f1_score(precision, recall)
    log.update({
        "conf mat": conf_mat,
        "class prec": precision,
        "class rec": recall,
        "f1": f1,
        "avg prec": sum(precision) / len(precision),
        "avg rec": sum(recall) / len(recall),
        "avg f1": sum(f1) / len(f1)
    }
    )
    logger.info(log)

if __name__ == '__main__':
    args = argparse.ArgumentParser(description='PyTorch Template')
    args.add_argument('-c', '--config', default=None, type=str,
                      help='config file path (default: None)')
    args.add_argument('-r', '--resume', default=None, type=str,
                      help='path to image checkpoint (default: None)')
    args.add_argument('-r2', '--resume2', default=None, type=str,
                      help='path to hand checkpoint (default: None)')
    args.add_argument('-d', '--device', default=None, type=str,
                      help='indices of GPUs to enable (default: all)')

    config = ConfigParser.from_args(args)
    main(config)


import sys

if len(sys.argv)<2 or len(sys.argv)>2:
  exit()

input_file_name = sys.argv[1]

f = open(input_file_name, "r")

output_gml = "graph\n[\tdirected\t1\n"

#nodes
firstline = f.readline()
isNodeList = "Node:" in firstline

if isNodeList:
  while True:
    line = f.readline()

    print(line)

    if line=="" or line == "\n" :
      break;

    linearray = line.split(",")
    output_gml+="\tnode\n\t[\n\t\tid\t"+linearray[0]+"\n\t]\n"

#edges
  firstline = f.readline()
  isNodeList = "Edge:" in firstline
  while True:
    line = f.readline()

    print(line)

    if line=="" or line == "\n" :
      break;

    linearray = line.split(",")
    output_gml+="\tedge\n\t[\n\t\tsource\t"+linearray[1]+"\n\t\ttarget\t"+linearray[2]+"\n\t]\n"

f.close();
output_gml+="]"
print(output_gml)

f = open(input_file_name+".gml", "a")
f.write(output_gml)
f.close()


from ADAFMNoiseReducer import ADAFMNoiseReducer
import cv2

if __name__ == "__main__":
    reducer = ADAFMNoiseReducer()
    img_path = "input.jpg"
    img = cv2.imread(img_path)
    img = reducer(img)
    cv2.imwrite("result.jpg", img)
    cv2.imshow("", img)
    cv2.waitKey()


""" Triangular numbers """

TRIANGULAR = int(input("Digite um número: "))

x: int = 1

while x * (x + 1) * (x + 2) < TRIANGULAR:
    x += 1

if x * (x + 1) * (x + 2) != TRIANGULAR:
    print(f"{TRIANGULAR} não é triangular")
else:
    print(f"{TRIANGULAR} é triangular")


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

# In[1]:

from sklearn.datasets import load_breast_cancer
cancer_data = load_breast_cancer()
cancer_data["feature_names"]

# In[2]:

import pandas as pd
df = pd.DataFrame(cancer_data.data, columns=cancer_data['feature_names'])
df['cancer'] = cancer_data.target
df.sample(5)

# In[3]:

faltantes = df.isnull().sum()
faltantes

# In[4]:

df.dtypes

# In[5]:

cols_to_scale =cancer_data['feature_names']
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
data_scaled = scaler.fit_transform(df[cols_to_scale])
df_scaled = pd.DataFrame(data_scaled,columns=cancer_data['feature_names'] )
df_scaled['cancer'] = df['cancer'].copy()
df_scaled.sample(5)

# In[6]:

X = data_scaled
y = df['cancer']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=5)

from sklearn.ensemble import VotingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier

log_clf = LogisticRegression()
rnd_clf = RandomForestClassifier()
svm_clf = SVC()
tree_clf = DecisionTreeClassifier()
knn_clf = KNeighborsClassifier()

voting_clf = VotingClassifier(
    estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf),('dt', tree_clf), ('knn', knn_clf) ],
    voting='hard')
voting_clf.fit(X_train, y_train)

# In[7]:

from sklearn.metrics import accuracy_score

for clf in (log_clf, rnd_clf, svm_clf, tree_clf, knn_clf,voting_clf):
    clf.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    print(clf.__class__.__name__, accuracy_score(y_test, y_pred))

# In[ ]:


"""Add delegated oauth models

Revision ID: a73e0b144fd3
Revises: e5f8d19beac2
Create Date: 2017-04-09 22:36:59.095173

"""

# revision identifiers, used by Alembic.
revision = 'a73e0b144fd3'
down_revision = 'e5f8d19beac2'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('oauthscope')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('oauthscope',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('created', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
    sa.Column('updated', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
    sa.Column('client_id', sa.INTEGER(), autoincrement=False, nullable=False),
    sa.Column('name', sa.VARCHAR(length=256), autoincrement=False, nullable=False),
    sa.Column('description', sa.VARCHAR(length=512), autoincrement=False, nullable=False),
    sa.Column('write', sa.BOOLEAN(), autoincrement=False, nullable=False),
    sa.ForeignKeyConstraint(['client_id'], ['oauthclient.id'], name='oauthscope_client_id_fkey'),
    sa.PrimaryKeyConstraint('id', name='oauthscope_pkey')
    )
    # ### end Alembic commands ###


import pandas as pd
from sportsreference.ncaaf.teams import Teams
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression

#import team stats
stats2015 = Teams("2015").dataframes
stats2016 = Teams("2016").dataframes
stats2017 = Teams("2017").dataframes
stats2018 = Teams("2018").dataframes
stats2019 = Teams("2019").dataframes

#drop Idaho from 2015-2017 stats
stats2015 = stats2015.drop("IDAHO")
stats2016 = stats2016.drop("IDAHO")
stats2017 = stats2017.drop("IDAHO")

#add in 2015-2016 stats for Coastal Carolina
cc2017 = stats2017.loc["COASTAL-CAROLINA"]
stats2015 = stats2015.append(cc2017)
stats2016 = stats2016.append(cc2017)

#add in 2015-2017 stats for Liberty
liberty2018 = stats2018.loc["LIBERTY"]
stats2015 = stats2015.append(liberty2018)
stats2016 = stats2016.append(liberty2018)
stats2017 = stats2017.append(liberty2018)

#add in 2015-2016 stats for UAB
uab2017 = stats2017.loc["ALABAMA-BIRMINGHAM"]
stats2015 = stats2015.append(uab2017)
stats2016 = stats2016.append(uab2017)

#import past game data
games2016 = pd.read_csv("cfb games 2016.csv")
games2017 = pd.read_csv("cfb games 2017.csv")
games2018 = pd.read_csv("cfb games 2018.csv")
games2019 = pd.read_csv("cfb games 2019.csv")

#subset
games2018 = games2018.iloc[134:735]
games2019 = games2019.iloc[139:]
current_games = pd.read_csv("current games.csv")

#create test stats
features = ["first_downs", "opponents_first_downs", "fumbles_lost",
            "opponents_fumbles_lost", "interceptions", "opponents_interceptions",
            "pass_attempts", "opponents_pass_attempts",  "pass_completions",
            "opponents_pass_completions", "pass_touchdowns", "opponents_pass_touchdowns",
            "pass_yards", "opponents_pass_yards", "penalties", "opponents_penalties",
            "points_against_per_game", "points_per_game", "rush_attempts",
            "opponents_rush_attempts", "rush_touchdowns", "opponents_rush_touchdowns",
            "rush_yards", "opponents_rush_yards", "yards", "opponents_yards", "turnovers",
            "opponents_turnovers", "yards_from_penalties",
            "opponents_yards_from_penalties"]

diff_features = ["d_" + feature for feature in features]
level_features = ["l_" + feature for feature in features]

diff_d = {feature:"d_" + feature for feature in features}
level_d = {feature:"l_" + feature for feature in features}

#create weighted stats
for feature in diff_features:
    current_games.insert(current_games.shape[1], feature, 0)
for feature in level_features:
    current_games.insert(current_games.shape[1], feature, 0)
weights = [n ** 2 for n in range(1, 6)]
years = [stats2015[features], stats2016[features], stats2017[features],
         stats2018[features], stats2019[features]]

weighted_stats = pd.DataFrame(index = years[0].index, columns = features)
weighted_stats = weighted_stats.fillna(0)
for i in range(len(years)):
    weight = years[i].multiply(weights[i])
    weighted_stats = weighted_stats.add(weight)
weighted_stats = weighted_stats.div(sum(weights))

for i in range(current_games.shape[0]):
    away_team = current_games.at[i, "away"]
    home_team = current_games.at[i, "home"]

    diff_stats = weighted_stats.loc[home_team] - weighted_stats.loc[away_team]
    diff_stats.rename(index = diff_d, inplace = True)
    current_games.loc[i, diff_features] = diff_stats

    level_stats = weighted_stats.loc[home_team]
    level_stats.rename(index = level_d, inplace = True)
    current_games.loc[i, level_features] = level_stats

#specify test and train
train = games2018
test = current_games

x_train = train[diff_features + level_features]
x_test = test[diff_features + level_features]

y_train = train["spread"]

#predict spreads
pca = PCA(n_components = 0.8, svd_solver = "full")
x_pca_train = pca.fit_transform(x_train)
x_pca_test = pca.transform(x_test)

pca_reg = LinearRegression()
pca_reg.fit(x_pca_train, y_train)
predictions = pd.Series(pca_reg.predict(x_pca_test), name = "predicted_spread")

#determine bet amount
def wager(budget, difference, odds = -110):
    def convert_odds(odds):
        if odds > 0:
            decimal_odds = odds + 1
        else:
            decimal_odds = 100 / -odds + 1
        return round(decimal_odds, 3)
    decimal_odds = convert_odds(odds)
    proportion = abs(difference) / decimal_odds
    bet = budget * min(proportion / 100, 0.05)
    return round(bet, 2)

#create prediction df
core = ["away", "home", "spread", "away_odds", "home_odds"]
predicted_spreads = current_games[core].join(predictions)

#generate bets
budget = 100
threshold = 4.5
cutoff = 18
picks = []
bets = []
differences = predicted_spreads.predicted_spread - predicted_spreads.spread
for i in range(predicted_spreads.shape[0]):
    if abs(predicted_spreads.at[i, "spread"]) < cutoff:
        if differences[i] < -threshold:
            picks.append(predicted_spreads.at[i, "away"])
            odds = predicted_spreads.at[i, "away_odds"]
            bet = wager(budget, differences[i], odds)
            bets.append(bet)
        elif differences[i] > threshold:
            picks.append(predicted_spreads.at[i, "home"])
            odds = predicted_spreads.at[i, "home_odds"]
            bet = wager(budget, differences[i], odds)
            bets.append(bet)
        else:
            picks.append("no pick")
            bets.append(0)
    else:
        picks.append("no pick")
        bets.append(0)

picks = pd.Series(picks, name = "picks")
bets = pd.Series(bets, name = "bets")
predicted_spreads = predicted_spreads.join([picks, bets])

#print bets
for i in range(predicted_spreads.shape[0]):
    series = predicted_spreads.loc[i]
    if series["picks"] != "no pick":
        pick = series["picks"]
        amount = series["bets"]
        print(amount, "on", pick)


import numpy as np
import random

def lawn_moving(mtrx, rn, res, st):
    for k in range(len(rn) - 1):
        if rn[k] < mtrx[st][0] and rn[k] > 0:
            res.append('State_0 => ')
            in_state = 0
        elif rn[k] > mtrx[st][0] and rn[k] <= (mtrx[st][0] + mtrx[st][1]):
            res.append('State_1 => ')
            in_state = 1
        else:
            res.append('State_2 => ')
            in_state = 2

    return res

def usual_chain(in_state):
    modelled_way = []
    rn = np.random.uniform(0,1,size = 11)
    print("Значення альфа: ")
    for j in range(len(rn)):
        print(rn[j], end=' ')
        print()
    initial_vctr = [0.3, 0.5, 0.2]
    if in_state != -1:
        initial = 'State_' + str(in_state) + ' => '
        modelled_way.append(initial)
    else:
        if rn[0] < initial_vctr[0]:
            modelled_way.append('State_0 => ')
            in_state = 0
        elif rn[0] > initial_vctr[0] and rn[0] <= (initial_vctr[0] + initial_vctr[1]):
            modelled_way.append('State_1 => ')
            in_state = 1
        else:
            modelled_way.append('State_2 => ')
            in_state = 2

    prob_matrix = [[0.1,0.2,0.7],
                   [0.3,0.6,0.1],
                   [0.6,0.2,0.2]]

    final_result = lawn_moving(prob_matrix, rn, modelled_way, in_state)
    print('Початкові ймовірності: \n', initial_vctr)
    print('Матриця ймовірностей:')
    for i in range(len(prob_matrix)):
        for j in range(len(prob_matrix[i])):
            print(prob_matrix[i][j], end=' ')
        print()
    print('Змодельований ланцюг:', ''.join(modelled_way))

while(True):
        s = input('Обрати початковий стан?(y/n)')
        if s == 'y':
            in_state = int(input('Оберіть початковий стан(від 0 до 2):'))
            usual_chain(in_state)
        else:
            usual_chain(-1)
        answer = input('Повторити операцію?(y/n):')
        if answer == 'y':
            continue
        else:
            break


import pandas as pd

from FamilyCreator import (
    find_and_filter_all_keys,
    get_element_tree,
    get_optionals,
    parse_xml_to_dict,
)

FEATURE_MODEL_NAME = "TuggerTrain"
INPUT_FILEPATH = f"./{FEATURE_MODEL_NAME}/feature_model/{FEATURE_MODEL_NAME}2.xml"
OUTPUT_FILEPATH = f"./{FEATURE_MODEL_NAME}/reconfiguration_sheet/{FEATURE_MODEL_NAME}_reconfiguration_sheet_template.csv"
DEFAULT_COLUMNS = [
    "#",
    "ContextInformation",
    "RelationshipType",
    "RelatedContextInformation",
    "Property",
    "ContextDomain",
    "Unit",
    "DataType",
]

def main():
    """
    This script reads all optional features from a feature model using functions from FamilyCreator.
    It creates an empty CSV file with all necessary default values and optional features in the header.
    The CSV file can then be used to set up the reconfiguration trigger.
    """
    # extract feature model from xml
    root1 = get_element_tree(INPUT_FILEPATH)
    f = parse_xml_to_dict(next(iter(root1)))
    fm1_keys = find_and_filter_all_keys(f)

    # determine optional features
    optionals = {}
    get_optionals(fm1_keys, f[next(iter(f))], optionals)

    # prepare imp and imp not columns for optional features
    optional_columns = sorted(
        [f"{o.split('#')[-1]} {i}" for o in optionals for i in ["(imp)", "(imp not)"]]
    )

    # create dataframe and convert to csv
    all_columns = DEFAULT_COLUMNS + optional_columns
    df = pd.DataFrame(columns=all_columns)
    df.to_csv(OUTPUT_FILEPATH, sep=";", index=False)

if __name__ in "__main__":
    main()


import cv2
import numpy as np

def medianfilter(_img, K_size = 3):
    img = _img.copy()
    out = _img.copy()
    pad = K_size//2

    if len(img.shape) == 3:
        H, W, C = img.shape

    else:
        img = np.expand_dims(img, axis = -1)
        H, W, C = img.shape

    H -= pad*2
    W -= pad*2

    # median
    for y in range(H):
        for x in range(W):
            for c in range(C):
                out[y+pad, x+pad, c] = np.median(img[y:y+2*pad+1, x:x+2*pad+1, c])
    out = out.astype(np.uint8)
    print(out)
    print(out.shape)
    print("ーーーーーーーーーーーーーーーーーーーーーーー")
    return out[pad:H+pad, pad:W+pad]

def zero_padding(_img,K_size = 3):
    img = _img.copy()
    pad = K_size//2
    out = np.pad(img, [(pad,pad),(pad,pad),(0,0)],"constant")
    return out

img = cv2.imread("./image_01_10/imori_noise.jpg").astype(np.float32)
print(img)
print(img.shape)
print("ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー")
img_zero = zero_padding(img)
img_ans = medianfilter(img_zero)

print(img_ans)
print(img_ans.shape)

cv2.imwrite("./image_01_10/answer10.jpg", img_ans)
cv2.imshow("result", img_ans)
cv2.waitKey(0)
cv2.destroyAllWindows()


# Reggie Jan Marc Nillo
# Game Idea No. 1

# RPG
# Might follow the classic Megami Tensei Route
import ActionList
import random

class unit():
    def __init__(self, UName, ULevel, UBHP, UBATK, UBSPD, UBDEF, UGHP, UGATK, UGSPD, UGDEF):
        self.Name = UName
        self.Level = ULevel
        self.BHP = UBHP
        self.BATK = UBATK
        self.BSPD = UBSPD
        self.BDEF = UBDEF
        self.GHP = UGHP
        self.GATK = UGATK
        self.GSPD = UGSPD
        self.GDEF = UGDEF
# End of class unit

class ActiveUnit(unit):
    def __init__(self, UName, ULevel, UBHP, UBATK, UBSPD, UBDEF, UGHP, UGATK, UGSPD, UGDEF):
        # Inheriting the unit class
        unit.__init__(self, UName, ULevel, UBHP, UBATK, UBSPD, UBDEF, UGHP, UGATK, UGSPD, UGDEF)
        # Unit's stats
        self.HP = int((round((self.Level - 1) * self.GHP,0) + self.BHP) * 10)
        self.ATK = int((round((self.Level - 1) * self.GATK,0) + self.BATK) * 5)
        self.SPD = int((round((self.Level - 1) * self.GSPD,0) + self.BSPD) * 5)
        self.DEF = int((round((self.Level - 1) * self.GDEF,0) + self.BDEF) * 5)
        # Unit's Sets
        self.skillList = []
        self.addSkill(ActionList.Basic_Attack)
        # Unit's Interval
        self.Interval = 0

    # Prints the Unit's Stats
    def printStats(self):
        print(f"Unit Analysis for {self.Name}")
        print(f"Level: {self.Level}")
        print(f"HP: {self.HP}")
        print(f"ATK: {self.ATK}")
        print(f"SPD: {self.SPD}")
        print(f"DEF: {self.DEF}")
        print("------------------------------------")

    def addSkill(self,skill):
        self.skillList.append(skill)

    # Find Skill
    def FindSkill(self):
        ASkill = random.choice(self.skillList)
        while ASkill.cooldown > 0:
            ASkill = random.choice(self.skillList)
        print(f"{self.Name} is going to use {ASkill.name}!")
        return ASkill

    # Find Targets
    def FindTargets(self, Skill, OtherTeam):
        Targets = []
        MinDef = 999999
        PrevMinDef = -999999
        RemTargets = 0
        if Skill.targets == 0: # 0 Means that the Skill will target everyone
            return OtherTeam
        else:
            while RemTargets < Skill.targets:
                TargetTeammate = None
                for someunit in OtherTeam:
                    if someunit.DEF > PrevMinDef and someunit.DEF < MinDef and someunit.HP > 0:
                        TargetTeammate = someunit
                Targets.append(TargetTeammate)
                MinDef = 999999
                RemTargets += 1
            TargetNames = []
            for someunit in Targets:
                TargetNames.append(someunit.Name)
            print(TargetNames)
            return Targets

    # Attack!
    def DoAction(self, Skill, KnownTargets):
        AttackPower = self.ATK * Skill.ATKMultiplier
        for someunit in KnownTargets:
            DamageDealt = 0
            # Calculate damage: AttackPower - defense
            DamageDealt = AttackPower - someunit.DEF
            if DamageDealt < 0:
                DamageDealt = 0 # What if an attack was so weak it heals?
            # Put that damage dealt into HP
            someunit.HP = someunit.HP - DamageDealt
            if someunit.HP <= 0:
                someunit.HP = 0
                print(f"{someunit.Name} has been KO'd!")
        # Then finally 0 out the interval
        self.Interval = 0
# End of class ActiveUnit


#! /usr/bin/env python

from ROOT import *
from array import array
from tdrStyle import *

setTDRStyle()

def plotvariations(ch):

    if ch is 'pho':
        f = TFile("atoz_unc.root","READ")
        channel = "znlo1_over_anlo1"
    if ch is 'w':
        f = TFile("wtoz_unc.root","READ")
        channel = "znlo012_over_wnlo012"

    h1  = f.Get(channel+"_central")
    h1.SetLineColor(1)
    h2 = f.Get(channel+"_CorrscaleUp")
    h2.SetLineColor(2)
    h3 = f.Get(channel+"_CorrscaleDown")
    h3.SetLineColor(2)
    h4 = f.Get(channel+"_pdfUp")
    h4.SetLineColor(4)
    h5 = f.Get(channel+"_pdfDown")
    h5.SetLineColor(4)
    h6 = f.Get(channel+"_UnCorrscaleUp")
    h6.SetLineColor(6)
    h7 = f.Get(channel+"_UnCorrscaleDown")
    h7.SetLineColor(6)
    h8 = f.Get(channel+"_UnCorr80scaleUp")
    h8.SetLineColor(8)
    h9 = f.Get(channel+"_UnCorr80scaleDown")
    h9.SetLineColor(8)

    f2 = TFile("atoz_ewkunc.root","READ")
    h10 = f2.Get("a_ewkcorr_up")
    h10.SetLineColor(40)
    h11 = f2.Get("a_ewkcorr_down")
    h11.SetLineColor(40)

    c4 = TCanvas("c4","c4", 900, 1000)

    # Add Legend
    legend = TLegend(.60,.70,.92,.92)
    legend . AddEntry(h1,"Central Value","l")
    legend . AddEntry(h2,"Correlated Scale Up/Down","l")
    legend . AddEntry(h7,"Uncorrelated Scale Up/Down","l")
    legend . AddEntry(h8,"Uncorrelated by 80% Scale Up/Down","l")
    legend . AddEntry(h4,"Pdf Up/Down","l")
    legend . AddEntry(h10,"Ewk Up/Down","l")

    h1.Draw("HIST")
    h1.GetYaxis().SetTitle('Sys on the Ratio')
    h1.GetYaxis().CenterTitle()
    h1.GetYaxis().SetTitleOffset(1.2)
    #h1.GetXaxis().SetLabelSize(0)
    h1.GetXaxis().SetTitle('Gen Boson Pt')
    h2.Draw("HISTsame")
    h3.Draw("HISTsame")
    h4.Draw("HISTsame")
    h5.Draw("HISTsame")
    h6.Draw("HISTsame")
    h7.Draw("HISTsame")
    h8.Draw("HISTsame")
    h9.Draw("HISTsame")
    h10.Draw("same")
    h11.Draw("same")
    legend.Draw("same")

    c4.SaveAs(ch+"ratio_unc.root")
    c4.SaveAs(ch+"ratio_unc.pdf")
    c4.SaveAs(ch+"ratio_unc.png")

#plotvariations("w")
plotvariations("pho")


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

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

# pylint: disable=protected-access,too-many-public-methods

from hamcrest import is_
from hamcrest import none
from hamcrest import is_not
from hamcrest import raises
from hamcrest import calling
from hamcrest import equal_to
from hamcrest import assert_that
does_not = is_not

import os
import shutil
import tempfile
from io import BytesIO

from nti.badges.openbadges.utils import load_data

from nti.badges.openbadges.utils.badgebakery import bake_badge
from nti.badges.openbadges.utils.badgebakery import process_args
from nti.badges.openbadges.utils.badgebakery import get_baked_data

from nti.badges.tests import NTIBadgesTestCase

class TestBadgeBakery(NTIBadgesTestCase):

    def test_png_url(self):
        path = os.path.join(os.path.dirname(__file__), 'ichigo.png')
        with open(path, "rb") as fp:
            PNG = fp.read()

        unbaked = BytesIO(PNG)
        assert_that(get_baked_data(unbaked), is_(none()))

        baked = BytesIO()
        unbaked = BytesIO(PNG)
        bake_badge(unbaked, baked, url='http://foo.org/assertion.json')

        baked = BytesIO(baked.getvalue())
        assert_that(get_baked_data(baked),
                    is_('http://foo.org/assertion.json'))

        baked = BytesIO(baked.getvalue())
        assert_that(get_baked_data(baked, raw=True),
                    is_('http://foo.org/assertion.json'))

        rebaked = BytesIO()
        baked = BytesIO(baked.getvalue())
        bake_badge(baked, rebaked, 'http://another/assertion')

        rebaked = BytesIO(rebaked.getvalue())
        assert_that(get_baked_data(rebaked), is_('http://another/assertion'))

    def test_coverage(self):
        path = os.path.join(os.path.dirname(__file__), 'ichigo.png')
        with open(path, "rb") as fp:
            PNG = fp.read()

        baked = BytesIO()
        unbaked = BytesIO(PNG)
        bake_badge(unbaked, baked, payload='asserted')
        assert_that(get_baked_data(baked),
                    is_('asserted'))

        baked = BytesIO()
        unbaked = BytesIO(PNG)
        bake_badge(unbaked, baked, payload='asserted', secret='123')
        assert_that(get_baked_data(baked),
                    is_(none()))

        assert_that(get_baked_data(baked, secret='1234'),
                    is_(none()))

        assert_that(get_baked_data(baked, secret='123'),
                    is_('asserted'))

        baked = BytesIO()
        unbaked = BytesIO(PNG)
        assert_that(calling(bake_badge).with_args(unbaked, baked, 'http://example/i.json', 'asserted'),
                    raises(ValueError))

    def test_process_args(self):
        img_dir = tempfile.mkdtemp(dir="/tmp")
        try:
            # prepare issuer
            path = os.path.join(os.path.dirname(__file__), 'ichigo.png')
            shutil.copy(path, os.path.join(img_dir, 'ichigo.png'))
            path = os.path.join(img_dir, 'ichigo.png')
            assert_that(process_args(['-v', img_dir + '/foo.png']),
                        is_(2))

            assertion = os.path.join(os.path.dirname(__file__),
                                     'assertion4.json')
            assert_that(process_args(['-v', '-p', assertion, img_dir + '/ichigo.png']),
                        is_(2))

            assertion = os.path.join(os.path.dirname(__file__),
                                     'assertion.json')
            assert_that(process_args(['-v', '-p', assertion, img_dir + '/ichigo.png']),
                        is_(0))
        finally:
            shutil.rmtree(img_dir, True)

    def test_png_payload(self):
        path = os.path.join(os.path.dirname(__file__), 'ichigo.png')
        with open(path, "rb") as fp:
            PNG = fp.read()

        baked = BytesIO()
        unbaked = BytesIO(PNG)
        payload = {'manga': 'bleach'}
        bake_badge(unbaked, baked, payload=payload)

        baked = BytesIO(baked.getvalue())
        baked_data = get_baked_data(baked)
        assert_that(baked_data, is_not(none()))
        baked_data = load_data(baked_data)
        assert_that(baked_data, is_(equal_to(payload)))


def visiblePoints(points):

    from math import atan2, pi

    maxView = 0
    field_width = 2*pi*(45.0001/360)

    angles = [atan2(y, x) % (2*pi) for x, y in points]
    angles.sort()

    # angle_differences = [j - i for i, j in zip(angles[:-1], angles[1:])]
    # if max(angle_differences)

    for x in angles:
        if x < field_width:
            angles.append(x+(2*pi))
        else:
            break

    for i, start_angle in enumerate(angles):
        for j in range(i, len(angles)):
            if angles[j] - angles[i] >= field_width:
                break
        temp = range(i, j)
        if len(temp) > maxView:
            maxView = len(temp)

    return maxView

if __name__=='__main__':
    points = [
        [1,1],#
        [3,1],
        [3,2],
        [3,3],#
        [1,3],#
        [2,5],#
        [1,5],#
        [-1,-1],
        [-1,-2],
        [-2,-3],
        [-4,-4]]
    points = [[5,4]]
    print(visiblePoints(points))


import math

class Vertex:

    def __init__(self, name, x, y,nodeId):
        """ initializes a vertex object """
        self.name = name
        self.x = x
        self.y = y
        self.nodeID=nodeId

    def __str__(self):
        res = self.name + "(" + str(self.x) + "," + str(self.y) + ")"
        return res

    def caculateDis(self, b):
        ax=abs(self.x-b.x)
        ay=abs(self.y-b.y)
        dis=(ax*ax+ay*ay)**0.5
        return dis

    def caculateAng(self, b):
        ax = b.x-self.x
        ay = b.y-self.y
        ang=int(math.atan2(ax, ay)*180/math.pi)
        return ang

# Sample test of basic functionalities given
# v1 = Vertex("A", 100, 200, 1)
# print(v1)


#!/usr/bin/python3
"""
Defines the class Student
"""

class Student:
    """Student instances"""

    def __init__(self, first_name: str, last_name: str, age: int):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def to_json(self) -> dict:
        student_dict = {
            "first_name": self.first_name,
            "last_name": self.last_name,
            "age": self.age
        }
        return student_dict


#!/usr/bin/env python3
from datetime import datetime as dt

now = dt.now()

print('Starting X Color eta {}'.format(now))
from Color_Detector_Main import banners, banner

try:
    banners(banner)
    from Color_Detector import get_colors, get_image, RGB2HEX
except KeyboardInterrupt as Ke:
    print('\n Error the program was interrupted')

    def close():
        import sys
        waiter = 'Shutting down ' + '#' * 20 + '\n'
        for s in waiter:
            sys.stdout.write(s)
            sys.stdout.flush()
            import time
            time.sleep(0.2)
    print('please wait')
    close()
    print('Died {}'.format(now))


import pyglet

window = pyglet.window.Window()

cube = pyglet.image.load('C:/Users/Administrator/Desktop/Documents/small_ideas/rubiks_cube/tut/cube.png')

sprite = pyglet.sprite.Sprite(cube, x=50, y=50)

@window.event
def on_draw():
    window.clear()
    sprite.draw()

def update(dt):
    # Move 10 pixels per second
    sprite.x += dt * 10

# Call update 60 times a second
pyglet.clock.schedule_interval(update, 1/60.)

pyglet.app.run()


import unittest
import heapq

class Solution:
    def getSkyline(self, buildings):
        """
        :type buildings: List[List[int]]
        :rtype: List[List[int]]
        """
        sortedBuilding = sorted([(L, -H, R) for L, R, H in buildings] + list({(R, 0, None) for _, R, _ in buildings}))
        res, hp = [[0, 0]], [(0, float("inf"))]
        for x, negH, R in sortedBuilding:
            while x >= hp[0][1]:
                heapq.heappop(hp)
            if negH:
                heapq.heappush(hp, (negH, R))
            if res[-1][1] + hp[0][0] != 0:
                res.append([x, -hp[0][0]])
        return res[1:]

    def getSkylineSlow(self, buildings):
        """
        :type buildings: List[List[int]]
        :rtype: List[List[int]]
        """
        if not buildings:
            return []

        critical = []

        for b in buildings:
            critical += [[b[0], b[2]], [b[1], 0]]

        critical = sorted(critical, key=lambda x: x[0])

        for l, r, h in buildings:
            for i in range(len(critical)):
                x, y = critical[i]
                if y < h and x >= l and x < r:
                    critical[i][1] = h

        result = [critical[0]]

        for i in range(1, len(critical)):
            if critical[i][1] != critical[i - 1][1]:
                result.append(critical[i])

        return result

class TestFunc(unittest.TestCase):
    """Test fuction"""

    def test(self):
        target = Solution()
        expected = [[2, 10],[3, 15],[7, 12],[12, 0],[15, 10],[20, 8],[24, 0]]
        test = [ [2, 9, 10], [3, 7, 15], [5, 12, 12], [15, 20, 10], [19, 24, 8] ]
        self.assertEqual(expected, target.getSkyline(test))

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


class Person:

    TITLES = ('Dr', 'Mr', 'Mrs', 'Ms')

    def __init__(self, title, name, surname):
        if title not in self.TITLES:
            raise ValueError("%s is not a valid title." % title)

        self.title = title
        self.name = name
        self.surname = surname

if __name__ == "__main__":
    person = Person\
    (
        "Mrs",
        "Jane",
        "Doe"
    )

    print(person.title)
    print(person.name)
    print(person.surname)


from gi.repository import Wnck
import gi
import sys
gi.require_version('Wnck', '3.0')

screen = Wnck.Screen.get_default()
screen.force_update()
temp_windows = screen.get_windows()

for win in temp_windows:
    if (str(win.get_pid()) == sys.argv[1] or
        win.get_class_instance_name() == 'hydriam' or
            win.get_class_instance_name() == 'Hydriam'):
        win.set_window_type(5)
        win.set_skip_tasklist(True)
        win.set_skip_pager(True)
        win.unshade()


import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from static.routers import advanced, analysis, enrichment, edit
from internal.tasks import document_enrichment, document_annotation

app = FastAPI()
templates = Jinja2Templates(directory="static/templates")
app.mount("/static", StaticFiles(directory="static"), name="static")

# Looks up other modules for  the creation of new pages.
app.include_router(advanced.router)
app.include_router(analysis.router)
app.include_router(enrichment.router)
app.include_router(edit.router)
app.include_router(document_enrichment.router)
app.include_router(document_annotation.router)

@app.get("/", response_class=HTMLResponse)
def get_start_page(request: Request):
    """ Creates the page for the starting page. """
    return templates.TemplateResponse("start.html", {"request": request, })

@app.get("/about", response_class=HTMLResponse)
def get_about(request: Request):
    """ Creates the page for the starting page. """
    return templates.TemplateResponse("about.html", {"request": request})

if __name__ == '__main__':
    uvicorn.run("main:app")


import os
import numpy as np
import pylab as pl
from simutil import *

#pylint: disable=undefined-variable

# What to do:
# DoSimObs = True
# DoFit = True
# casaexe = 'casa --nologger'

# Array to use:
arrayconfig = 'pdbi-a.cfg'

# Gain corruption factor:
Gfac = 1.5

# Center Freq:
Nu = '150.0GHz'

# Image size (pixels)
Npix = 1000

# Pixel size:
cell = '0.01arcsec'
cellN = 0.01

# Number of frequency channels:
Nnu = 100

# Channel width:
ChW = '0.01GHz'

# Total integration time:
Ttot = '3600s'

# For test 5:
imname = 'Gaussian'
# type   flux    major       minor       PA  freq   spec.ind.    Direction
s = ['gaussian', 3.5, '1.5arcsec', '1.0arcsec',
     '45.0deg', Nu, 0.0, "J2000 10h00m00.0s +10d00m02.0s"]

config = '.'.join(arrayconfig.split('.')[:-1])

vis = '%s/%s.%s.ms' % (imname, imname, arrayconfig.split('.')[0])

if DoSimObs:
    # TEST 5: ANTENNA GAIN FIT FOR PdB SIMULATION, COUPLED TO SOURCE PARAMETERS

    # FOR THE LATEST CASA VERSION (5.4):
    # SIMOBSERVE IS COMPLETELY BROKEN IF WE WANT TO SIMULATE ARRAYS OTHER THAN NRAO's ONES.
    # WE HAVE TO SWTICH TO THE SM TOOL.

    os.system('rm -rf %s*' % imname)
    cl.done()

    # for si in s:
    cl.addcomponent(dir=s[7], flux=s[1], fluxunit='Jy', freq=s[5], shape=s[0],
                    majoraxis=s[2], minoraxis=s[3], positionangle=s[4],
                    spectrumtype='spectral index', index=s[6])

    ia.fromshape(imname+'.model', [Npix, Npix, 1, Nnu], overwrite=True)
    cs = ia.coordsys()
    cs.setunits(['rad', 'rad', '', 'Hz'])
    cell_rad = qa.convert(qa.quantity(cell), "rad")['value']
    cs.setincrement([-cell_rad, cell_rad], 'direction')
    rdi, ddi = s[7].split()[1:]
    cs.setreferencevalue([qa.convert(rdi, 'rad')['value'],
                          qa.convert(ddi, 'rad')['value']], type="direction")
    cs.setreferencevalue(s[5], 'spectral')
    cs.setreferencepixel(0, 'spectral')

    cs.setincrement(ChW, 'spectral')
    ia.setcoordsys(cs.torecord())
    ia.setbrightnessunit("Jy/pixel")
    ia.modify(cl.torecord(), subtract=False)
    ia.close()

    os.system('mkdir %s' % imname)
    sm.open(vis)

    # Setting the observatory and the observation:
    util = simutil('')
    antlist = os.getenv("CASAPATH").split(' ')[0] + "/data/alma/simmos/" + arrayconfig
    stnx, stny, stnz, stnd, antnames, arrname, arrpos = util.readantenna(antlist)

    # CASA dictatorship imposes limits to observatory names:
    ARR = me.observatory('VLBA')

    H0 = 0.0
    refdate = '2017/01/01/00:00:00'
    usehourangle = True
    mount = 'alt-az'
    integ = '2s'

    sm.setconfig(telescopename='VLBA', x=stnx, y=stny, z=stnz,
                 dishdiameter=stnd.tolist(),
                 mount=mount, antname=antnames, padname=antnames,
                 coordsystem='global', referencelocation=ARR)

    sm.setspwindow(spwname='spsim', freq=Nu,
                   deltafreq=ChW,
                   freqresolution=ChW,
                   nchannels=Nnu, refcode="BARY",
                   stokes='RR')

    sm.setfield(sourcename='SIM5', sourcedirection=s[7],
                calcode="TARGET", distance='0m')

    mereftime = me.epoch('TAI', refdate)

    sm.settimes(integrationtime=integ, usehourangle=True,
                referencetime=mereftime)
    sm.observemany(sourcenames=['SIM5'], spwname='spsim', starttimes=['0s'],
                   stoptimes=[Ttot], project='polsimulate')
    sm.close()

    clearcal(vis=vis, addmodel=True)
    ft(vis=vis, usescratch=True, spw='0', field='SIM5', model=imname+'.model')

    ms.open(vis, nomodify=False)
    ms.selectinit(datadescid=0)
    CDAT = ms.getdata(['data', 'model_data'])
    CDAT['data'][:] = CDAT['model_data']
    ms.putdata(CDAT)
    ms.close()

    os.system('cp -rf %s %s.noisy' % (vis, vis))

    sm.openfromms('%s.noisy' % vis)
    sm.setdata(fieldid=[0], spwid=0)
    sm.setnoise(trx=50.,
                tau=0.05, tatmos=260., tground=290., tcmb=2.725,
                mode="tsys-manual", senscoeff=-1)
    sm.corrupt()
    sm.done()

    sm.close()

    # GAIN CORRUPTION:
    # The gain of antenna #2 will increase from 1 to Gfac during the
    # first half of the experiment. Then, it will be kept constant = Gfac

    # Get time range of observations:
    ms.open('%s.noisy' % vis)
    trange = ms.range(['time'])['time']/86400.
    ms.close()

    # time at half of the experiment:
    tmed = np.average(trange)

    # Change gain of antenna 2:
    ms.open('%s.noisy' % vis, nomodify=False)

    ms.selectinit(datadescid=0)
    data = ms.getdata(['data', 'antenna1', 'antenna2', 'time'])
    def GainFac(t):
        Gfunc = np.ones(np.shape(t))
        mask = t < tmed
        Gfunc[mask] = 1.0 + (t[mask]-trange[0])/(tmed-trange[0])*(Gfac - 1.)
        Gfunc[np.logical_not(mask)] = Gfac
        return Gfunc

    Gfunc = GainFac(data['time']/86400.)

    mask = data['antenna2'] == 2
    data['data'][:, :, mask] *= Gfunc[mask]
    mask = data['antenna1'] == 2
    data['data'][:, :, mask] *= Gfunc[mask]
    ms.putdata(data)
    ms.close()

if DoFit:
    print("---------------------------------------------")
    print("TEST 5")
    print("---------------------------------------------")
    # Get time range of observations:
    ms.open('%s.noisy' % vis)
    trange = ms.range(['time'])['time']/86400.
    ms.close()

    tmed = np.average(trange)

    tempfile = open('STEP5_FIT.py', 'w')

    # Source parameters:
    Gvar = '0.,0.,p[0],p[1],p[2],p[3]'

    ma = float(s[2].split('a')[0])
    mi = float(s[3].split('a')[0])
    pa = float(s[4].split('d')[0])

    # Last 2 params are those of the gain model function
    # (we will use a piece-wise linear function).
    # Both gains are set below their true value
    # (the solution is unstable if one is too high and
    # the other is too low).
    Pars = [s[1], ma, mi/ma, pa, 1., Gfac]
    BiasFac = [0.7, 1.3, 0.8, 0.75, 0.8, 0.8]

    Trues = Pars

    string = 'LMtune = [1.e-5,10.,1.e-5,10]'
    print >> tempfile, string

    string = 'S = [%.3e, %.3e, %.3e, %.3e, %.3e, %.3e]' % tuple(Pars)
    print >> tempfile, string

    string = "visname = '%s'" % ('%s.noisy' % vis)
    print >> tempfile, string

    # Define the gain function for antenna #2:
    gainFunc = 'pieceWise(p[4],p[5],%.8e,%.8e)' % (0., (tmed-trange[0])*86400.)
    string = "amp_gains = {2:'%s'}" % gainFunc
    print >> tempfile, string

    if s[0] == 'disk':
        s[0] = 'disc'
    if s[0] == 'gaussian':
        s[0] = 'Gaussian'

    string = "modelshape = ['%s']" % s[0]
    print >> tempfile, string

    NuF = float(Nu.split('G')[0])*1.e9
    string = "modvars = ['%s']" % Gvar
    print >> tempfile, string

    string = 'pini = [%.6e, %.6e, %.6e, %.6e, %.6e, %.6e]' % tuple(
        [Pars[pi]*BiasFac[pi] for pi in range(len(Pars))])
    print >> tempfile, string

    string = 'parbound = [[0.,None],[0.,None],[0.,None],[0.,90.],[0.75,1.25],[1.1,1.9]]'
    # ll = []
    # for pi in range(len(Pars)):
    #   ll += [Pars[pi]*(1. - BiasFac[pi]),Pars[pi]*(1. + BiasFac[pi])]
    # string = 'parbound = [[%.6e,%.6e],[%.6e,%.6e],[%.6e,%.6e],[%.6e,%.6e],[%.6e,%.6e],[%.6e,%.6e]]'%tuple(ll)
    print >> tempfile, string

    string = "STK = 'RR'"
    print >> tempfile, string

    lines = open('test5.py')
    for l in lines.readlines():
        print >> tempfile, l[:-1]
    lines.close()
    tempfile.close()

    pl.ioff()
    Cfile = 'TEST5.CLEAN'
    Rfile = 'TEST5.RESIDUALS'
    clearcal('%s.noisy' % vis)

    os.system('rm -rf %s.*' % Cfile)
    os.system('rm -rf %s.*' % Rfile)

    tclean('%s.noisy' % vis,
           imagename=Cfile, cell=cell,
           imsize=Npix, niter=0)

    ia.open('%s.image' % Cfile)
    resdat = ia.getchunk()[:, :, 0, 0]
    ia.close()
    fig = pl.figure()
    sub = fig.add_subplot(111)
    IMsize = cellN*Npix/2.
    ims = sub.imshow(np.transpose(resdat), origin='lower',
                     extent=[IMsize, -IMsize, -IMsize, IMsize])
    sub.set_xlabel('RA offset (mas)')
    sub.set_ylabel('Dec offset (mas)')
    cb = pl.colorbar(ims)
    cb.set_label('Jy/beam')
    pl.savefig('%s.png' % Cfile)

    impeak = np.max(resdat)

    os.system('%s -c STEP5_FIT.py' % casaexe)

    os.system('rm -rf %s.*' % Rfile)
    tclean('%s.noisy' % vis,
           imagename=Rfile, cell=cell,
           imsize=Npix, niter=0)

    impeak *= 0.01

    ia.open('%s.image' % Rfile)
    resdat = ia.getchunk()[:, :, 0, 0]
    ia.close()
    fig = pl.figure()
    sub = fig.add_subplot(111)
    IMsize = cellN*Npix/2.
    ims = sub.imshow(np.transpose(resdat), vmax=impeak,
                     origin='lower', extent=[IMsize, -IMsize, -IMsize, IMsize])
    sub.set_xlabel('RA offset (mas)')
    sub.set_ylabel('Dec offset (mas)')
    cb = pl.colorbar(ims)
    cb.set_label('Jy/beam')
    pl.savefig('%s.png' % Rfile)


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms
from torchvision.utils import save_image

device = 'cpu'

classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
classes_one_hot = F.one_hot(torch.arange(0, 10), num_classes=len(classes))

label_1 = 'deer'
label_2 = 'frog'
loaded_epoch = 500
interpolation_steps = 9
latent_size = 100
n_classes = len(classes)
filter_size_g = 96

for i, label in enumerate(classes):
    if classes[i] == label_1:
        label_1 = i
    if classes[i] == label_2:
        label_2 = i

class Generator(nn.Module):

    def __init__(self, latent_size, nb_filter, n_classes):
        super(Generator, self).__init__()

        self.embedding = nn.Linear(n_classes, latent_size)

        self.layer1 = nn.Sequential(nn.ConvTranspose2d(latent_size, nb_filter * 8, 4, 1, 0, bias=False),
                                    nn.ReLU(True))

        self.layer2 = nn.Sequential(nn.ConvTranspose2d(nb_filter * 8, nb_filter * 4, 4, 2, 1, bias=False),
                                    nn.BatchNorm2d(nb_filter * 4),
                                    nn.ReLU(True))

        self.layer3 = nn.Sequential(nn.ConvTranspose2d(nb_filter * 4, nb_filter * 2, 4, 2, 1, bias=False),
                                    nn.BatchNorm2d(nb_filter * 2),
                                    nn.ReLU(True))

        self.layer4 = nn.Sequential(nn.ConvTranspose2d(nb_filter * 2, nb_filter, 4, 2, 1, bias=False),
                                    nn.BatchNorm2d(nb_filter),
                                    nn.ReLU(True))

        self.layer5 = nn.Sequential(nn.ConvTranspose2d(nb_filter, 3, 4, 2, 1, bias=False),
                                    nn.Tanh())

    def forward(self, latent, label):
        label_embedding = self.embedding(label)
        x = torch.mul(label_embedding, latent)
        x = x.view(x.size(0), -1, 1, 1)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)
        x = self.layer5(x)

        return x

def weighing(label_one_hot, weight):
    label_one_hot = classes_one_hot[label_one_hot].to(device)
    label_one_hot = label_one_hot.tolist()
    label_one_hot = [item for elem in label_one_hot for item in elem]

    for i, value in enumerate(label_one_hot):
        if label_one_hot[i] == 1:
            label_one_hot[i] = weight

    label_one_hot = torch.FloatTensor(label_one_hot).to(device)

    return label_one_hot

G = Generator(latent_size, filter_size_g, n_classes).to(device)
G.load_state_dict(torch.load('checkpoints/checkpoint epoch {}.pt'.format(loaded_epoch), map_location=device))
G.eval()

transform_PIL = transforms.ToPILImage()

latent_value = torch.randn(1, 100).to(device)

label_1 = torch.LongTensor([label_1])
label_2 = torch.LongTensor([label_2])

# generate the images
for i in range(interpolation_steps):
    if i == 0:
        w_1 = 0
        w_2 = 1

    else:
        w_1 += 1 / (interpolation_steps - 1)
        w_2 = 1 - w_1

    label_1_one_hot = weighing(label_1, w_1).to(device)
    label_2_one_hot = weighing(label_2, w_2).to(device)

    label_combined = label_1_one_hot + label_2_one_hot.to(device)
    label_combined = label_combined.view(1, 10)

    img = G(latent_value, label_combined)

    save_image(img,
               'samples gradual/{}_{}_{:.2f}_{}_{:.2f}.png'.format(i + 1, classes[label_2], w_2, classes[label_1], w_1),
               padding=2, normalize=True)


from fastapi import APIRouter

from backend.src.dependencies.dependencies import TelegramDep

router = APIRouter(
    prefix='/user',
    tags=['user'],
    responses={404: {'description': 'Not found'}}
)

@router.post('/calendar/{uuid}/user/add')
async def add_user_to_calendar(telegram_credentials: TelegramDep, uuid: str):
    return NotImplemented

@router.post('/calendar/{uuid}/user/remove')
async def remove_user_from_calendar(telegram_credentials: TelegramDep, uuid: str):
    return NotImplemented

@router.post('/calendar/{uuid}/user/change_role')
async def change_user_role(telegram_credentials: TelegramDep, uuid: str):
    return NotImplemented


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.graphics.tsaplots as sgt
from statsmodels.tsa.arima.model import ARIMA
from scipy.stats.distributions import chi2
import statsmodels.tsa.stattools as sts

#Load Data
df_raw = pd.read_csv("./Data/index2018.csv")

#Data Sanitization--------------
df_copy = df_raw.copy()
df_copy.date = pd.to_datetime(df_copy.date, dayfirst = True)
df_copy.set_index("date", inplace=True)
df_copy=df_copy.asfreq('b')
df_copy=df_copy.fillna(method='ffill')
df_copy['market_value']=df_copy.spx

del df_copy['spx']
del df_copy['dax']
del df_copy['ftse']
del df_copy['nikkei']
size = int(len(df_copy)*0.8)
df, df_test = df_copy.iloc[:size], df_copy.iloc[size:]
#---------------------------------------

# Use ACF plot to analyze coefficients for MA

#------------------- Find MA 1
# The (p,d,q) order of the model for the autoregressive, differences, and moving
model_ma_1 = ARIMA(df.market_value, order=(0,0,1)) #q = 1,for MA only
results_ma_1 = model_ma_1.fit()
print(results_ma_1.summary())

#------------------- Find MA 2
model_ma_2 = ARIMA(df.market_value, order=(0,0,2)) #q = 2,for MA only
results_ma_2 = model_ma_2.fit()
print(results_ma_2.summary())
#In Summary P > |z| should be lower, the lower the better

#Define a Log Likelihood Ratio (LLR) test to compare the models
def LLR_test(mod_1, mod_2, DF=1):
    L1 = mod_1.fit().llf
    L2 = mod_2.fit().llf
    LR = (2*(L2-L1))
    p = chi2.sf(LR, DF).round(3)
    return p

print("LLR Test:",LLR_test(model_ma_1, model_ma_2)) #0.0 is consodered high value

#------------ Print resisulta
print("Residuals:",results_ma_2.resid)

#round(value, 3): Round value to 3 decimals


"""The CarliniWagnerL2 attack."""
import torch

INF = float("inf")

def carlini_wagner_l2(
    model_fn,
    x,
    n_classes,
    y=None,
    targeted=False,
    lr=0.005,
    confidence=0,
    clip_min=0,
    clip_max=1,
    initial_const=1e-2, #用于初始化二分搜索的常数项。
    binary_search_steps=5, #二分搜索的步数，用于搜索最小的常数项
    max_iterations=50, #最大迭代次数，表示生成对抗样本的最大迭代次数。
):
    """
    This attack was originally proposed by Carlini and Wagner. It is an
    iterative attack that finds adversarial examples on many defenses that
    are robust to other attacks.
    Paper link: https://arxiv.org/abs/1608.04644

    At a high level, this attack is an iterative attack using Adam and
    a specially-chosen loss function to find adversarial examples with
    lower distortion than other attacks. This comes at the cost of speed,
    as this attack is often much slower than others.

    :param model_fn: a callable that takes an input tensor and returns
              the model logits. The logits should be a tensor of shape
              (n_examples, n_classes).
    :param x: input tensor of shape (n_examples, ...), where ... can
              be any arbitrary dimension that is compatible with
              model_fn.
    :param n_classes: the number of classes.
    :param y: (optional) Tensor with true labels. If targeted is true,
              then provide the target label. Otherwise, only provide
              this parameter if you'd like to use true labels when
              crafting adversarial samples. Otherwise, model predictions
              are used as labels to avoid the "label leaking" effect
              (explained in this paper:
              https://arxiv.org/abs/1611.01236). If provide y, it
              should be a 1D tensor of shape (n_examples, ).
              Default is None.
    :param targeted: (optional) bool. Is the attack targeted or
              untargeted? Untargeted, the default, will try to make the
              label incorrect. Targeted will instead try to move in the
              direction of being more like y.
    :param lr: (optional) float. The learning rate for the attack
              algorithm. Default is 5e-3.
    :param confidence: (optional) float. Confidence of adversarial
              examples: higher produces examples with larger l2
              distortion, but more strongly classified as adversarial.
              Default is 0.
    :param clip_min: (optional) float. Minimum float value for
              adversarial example components. Default is 0.
    :param clip_max: (optional) float. Maximum float value for
              adversarial example components. Default is 1.
    :param initial_const: The initial tradeoff-constant to use to tune the
              relative importance of size of the perturbation and
              confidence of classification. If binary_search_steps is
              large, the initial constant is not important. A smaller
              value of this constant gives lower distortion results.
              Default is 1e-2.
    :param binary_search_steps: (optional) int. The number of times we
              perform binary search to find the optimal tradeoff-constant
              between norm of the perturbation and confidence of the
              classification. Default is 5.
    :param max_iterations: (optional) int. The maximum number of
              iterations. Setting this to a larger value will produce
              lower distortion results. Using only a few iterations
              requires a larger learning rate, and will produce larger
              distortion results. Default is 1000.
    """

    def compare(pred, label, is_logits=False):
        """
        A helper function to compare prediction against a label.
        Returns true if the attack is considered successful.

        :param pred: can be either a 1D tensor of logits or a predicted
                class (int).
        :param label: int. A label to compare against.
        :param is_logits: (optional) bool. If True, treat pred as an
                array of logits. Default is False.
        """

        # Convert logits to predicted class if necessary
        if is_logits:
            pred_copy = pred.clone().detach()
            pred_copy[label] += -confidence if targeted else confidence
            pred = torch.argmax(pred_copy)

        return pred == label if targeted else pred != label

    if y is None:
        # Using model predictions as ground truth to avoid label leaking
        pred = model_fn(x)
        y = torch.argmax(pred, 1)

    # Initialize some values needed for binary search on const
    lower_bound = [0.0] * len(x)
    upper_bound = [1e10] * len(x)  # 限制对抗干扰的上限和下限范围
    const = x.new_ones(len(x), 1) * initial_const #const是一个与输入x形状相同的张量，每个元素都初始化为initial_const的值。这个张量用于初始化二分搜索的常数项。

    o_bestl2 = [INF] * len(x) #是一个列表，长度为x的数量，初始时每个元素被设置为正无穷大（INF）。它用于记录生成的最佳对抗样本的L2距离。
    o_bestscore = [-1.0] * len(x) #也是一个列表，长度为x的数量，初始时每个元素被设置为-1.0。它用于记录生成的最佳对抗样本的得分（分数）。
    x = torch.clamp(x, clip_min, clip_max)
    ox = x.clone().detach()  # 它用于保存原始的输入图像，以便在需要时进行比较和恢复。
    o_bestattack = x.clone().detach() #它用于保存生成的最佳对抗样本，以便在更新时进行替换。

    # Map images into the tanh-space
    x = (x - clip_min) / (clip_max - clip_min) #归一化，放到0-1之间。
    x = torch.clamp(x, 0, 1) # 裁剪，确保指在0-1之间。
    x = x * 2 - 1 #将值缩放到 [-1, 1] 的范围内，即将值映射到 [-1, 1] 的范围。
    x = torch.arctanh(x * 0.999999) #进行反双曲正切变换，将其转换为位于 (-inf, inf) 范围内的值。该变换有助于保持输入数据的均匀分布，以便在对抗攻击算法中进行优化。

    # Prepare some variables
    modifier = torch.zeros_like(x, requires_grad=True) #义了一个和输入 x 相同大小的张量 modifier，并将其设置为需要梯度计算。这个 modifier 将用于存储对输入 x 进行扰动的值。

    # 离散化处理，将收益率映射到整数标签
    returns_min = y.min().item()
    returns_max = y.max().item()
    returns_range = returns_max - returns_min
    y = ((y - returns_min) / returns_range * (n_classes - 1)).to(torch.int)

    y_onehot = torch.nn.functional.one_hot(y.to(torch.int64), n_classes).to(torch.float)#这样的转换将目标标签表示为一个向量，其中只有目标类别对应的位置为1，其他位置为0。

    # Define loss functions and optimizer
    f_fn = lambda real, other, targeted: torch.max(
        ((other - real) if targeted else (real - other)) + confidence,
        torch.tensor(0.0).to(real.device), # confidence是一个常数项。然后将计算结果和零取最大值，使用 torch.max 函数进行比较。
    )
    l2dist_fn = lambda x, y: torch.pow(x - y, 2).sum(list(range(len(x.size())))[1:])#list(range(len(x.size())))[1:] 来忽略批次维度，只计算特征维度上的差的平方和。
    optimizer = torch.optim.Adam([modifier], lr=lr)#l2dist_fn用于计算两个张量之间的 L2 距离。计算它们之间的差的平方和

    # Outer loop performing binary search on const
    for outer_step in range(binary_search_steps):
        # Initialize some values needed for the inner loop
        bestl2 = [INF] * len(x) #bestl2 列表中的每个元素被设置为一个较大的值 INF，以确保在内部循环中找到的最小L2距离可以被更新。
        bestscore = [-1.0] * len(x)  # bestscore 列表中的每个元素被设置为 -1.0，以确保在内部循环中找到的最佳分数可以被更新。

        # Inner loop performing attack iterations
        for i in range(max_iterations):
            # One attack step
            new_x = (torch.tanh(modifier + x) + 1) / 2 #根据 modifier 对输入 x 进行扰动，
            new_x = new_x * (clip_max - clip_min) + clip_min  # 逆归一化的操作，使得数值返回到原始的数值。
            logits = model_fn(new_x)
            #y_onehot 与模型的输出 logits 进行相乘。这样得到的结果是一个张量，其中每个元素表示对应样本的目标类别得分。沿着第一维度求和，得到每个样本的目标类别得分 real。
            real = torch.sum(y_onehot * logits, 1)
            other, _ = torch.max((1 - y_onehot) * logits - y_onehot * 1e4, 1) #计算其他类别的最大得分 other。
            #计算对抗攻击的损失函数
            optimizer.zero_grad()
            f = f_fn(real, other, targeted)
            l2 = l2dist_fn(new_x, ox) #计算了对抗样本 new_x 与原始样本 ox 之间的 L2 距离 l2。
            loss = (const * f + l2).sum() #将损失函数定义为 const * f + l2，其中 const 是用于平衡两个项的常数。
            loss.backward()
            optimizer.step()

            # Update best results
            for n, (l2_n, logits_n, new_x_n) in enumerate(zip(l2, logits, new_x)):
                y_n = y[n] #获取样本的真实标签 y_n。
                succeeded = compare(logits_n, y_n, is_logits=True)#检查预测结果是否与真实标签一致，且返回的 succeeded 表示攻击是否成功。
                if l2_n < o_bestl2[n] and succeeded:
                    pred_n = torch.argmax(logits_n)
                    o_bestl2[n] = l2_n
                    o_bestscore[n] = pred_n
                    o_bestattack[n] = new_x_n
                    # l2_n < o_bestl2[n] implies l2_n < bestl2[n] so we modify inner loop variables too
                    bestl2[n] = l2_n
                    bestscore[n] = pred_n
                elif l2_n < bestl2[n] and succeeded:
                    bestl2[n] = l2_n
                    bestscore[n] = torch.argmax(logits_n)

        # Binary search step
        for n in range(len(x)):
            y_n = y[n]
        #如果最佳预测结果与真实标签一致且不为 -1，表示攻击成功，此时将 const[n] 的上界 upper_bound[n] 更新为当前 const[n] 与 upper_bound[n] 的较小值，即缩小 const[n] 的取值范围。
            if compare(bestscore[n], y_n) and bestscore[n] != -1:#并确保最佳预测结果不为 -1（表示攻击成功）。
                # Success, divide const by two
                upper_bound[n] = min(upper_bound[n], const[n])
                if upper_bound[n] < 1e9:
                    const[n] = (lower_bound[n] + upper_bound[n]) / 2
            else:
                # Failure, either multiply by 10 if no solution found yet
                # or do binary search with the known upper bound
                lower_bound[n] = max(lower_bound[n], const[n])
                if upper_bound[n] < 1e9:
                    const[n] = (lower_bound[n] + upper_bound[n]) / 2
                else:
                    const[n] *= 10
        # 上面的代码就是这段代码用于控制对抗攻击中的上界和下界，这里的目标是找到一个合适的 const 值，以控制对抗攻击的强度。const 是一个用于控制损失函数中两个部分（即对抗项和 L2 距离项）权重的常数项。
    return o_bestattack.detach()

if __name__ == "__main__":
    x = torch.clamp(torch.randn(5, 10), 0, 1)
    y = torch.randint(0, 9, (5,))
    model_fn = lambda x: x

    # targeted
    new_x = carlini_wagner_l2(model_fn, x, 10, targeted=True, y=y)
    new_pred = model_fn(new_x)
    new_pred = torch.argmax(new_pred, 1)

    # untargeted
    new_x_untargeted = carlini_wagner_l2(model_fn, x, 10, targeted=False, y=y)
    new_pred_untargeted = model_fn(new_x_untargeted)
    new_pred_untargeted = torch.argmax(new_pred_untargeted, 1)


from __future__ import annotations

import ast

from flake8_pie.base import Error

def pie806_no_assert_except(node: ast.Try, errors: list[Error]) -> None:
    if (
        len(node.handlers) == 1
        and isinstance(node.handlers[0].type, ast.Name)
        and node.handlers[0].type.id == "AssertionError"
        and all(isinstance(x, ast.Assert) for x in node.body)
    ):
        errors.append(PIE806(lineno=node.lineno, col_offset=node.col_offset))

def PIE806(lineno: int, col_offset: int) -> Error:
    return Error(
        lineno=lineno,
        col_offset=col_offset,
        message="PIE806 no-assert-except: Instead of asserting and catching, use an if statment.",
    )


def sum_of_prime_numbers(limit):
    # Create a boolean array to mark numbers as prime or not
    is_prime = [True] * limit

    # Mark 0 and 1 as non-prime
    is_prime[0] = is_prime[1] = False

    #Sieve of Eratosthenes algorithm
    p = 2
    while p * p < limit:
        if is_prime[p]:
            for i in range(p * p, limit, p):
                is_prime[i] = False
        p += 1

    # Calculating sum of prime numbers
    prime_sum = sum(num for num in range(limit) if is_prime[num])

    return prime_sum

# Calculating sum of primes below 200,000
limit = 200000
prime_sum = sum_of_prime_numbers(limit)

print("Sum of primes below", limit, ":", prime_sum)