import torch
import os
from PIL import Image
from torch.utils.data import Dataset
import pandas as pd
import random
from PIL import Image
from torchvision import transforms

class TripletAntsDataset(Dataset):
    """
    Dataset class for the triplet ants dataset. Returns a triplet of images and the label of the
    anchor image.
    """

    def __init__(self, csv_file, root_dir, transform=None):
        """
        Arguments:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        if isinstance(csv_file, pd.DataFrame):
            self.labels = csv_file
        elif isinstance(csv_file, str):
            self.labels = pd.read_csv(csv_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        anchor_path = os.path.join(self.root_dir,               # Directory to all ant folders
                                self.labels.iloc[idx, 0],       # Directory to specific ant folder
                                self.labels.iloc[idx, 1])       # Filename of anchor image

        anchor_image = Image.open(anchor_path)

        positive_path = anchor_path
        while positive_path == anchor_path:
            pos_img_name = random.choice(os.listdir(os.path.join(self.root_dir, self.labels.iloc[idx, 0])))
            positive_path = os.path.join(self.root_dir,
                                         self.labels.iloc[idx, 0],
                                         pos_img_name)

        positive_image = Image.open(positive_path)

        positive_dir=  os.path.join(self.root_dir,               # Directory to all ant folders
                                self.labels.iloc[idx, 0])       # Directory to specific ant folder
        negative_dir = positive_dir

        while negative_dir == positive_dir:
            negative_dir = random.choice(os.listdir(self.root_dir))

            negative_dir_path = os.path.join(self.root_dir, negative_dir)
            if os.path.isfile(negative_dir_path):
                negative_dir = positive_dir
                continue

            neg_img_name = random.choice(os.listdir(negative_dir_path))
            negative_path = os.path.join(negative_dir_path, neg_img_name)

        negative_image = Image.open(negative_path)

        if self.transform:
            anchor_image = self.transform(anchor_image)
            positive_image = self.transform(positive_image)
            negative_image = self.transform(negative_image)

        return anchor_image, positive_image, negative_image, str(self.labels.iloc[idx, 0])

class AntsDataset(Dataset):
    """
    Dataset class for the ants dataset. Returns an image and the label of the image.
    """

    def __init__(self, csv_file, root_dir, transform=None):
        """
        Arguments:
            csv_file (string): Path to the csv file with annotations.
            root_dir (string): Directory with all the images.
            transform (callable, optional): Optional transform to be applied
                on a sample.
        """
        if isinstance(csv_file, pd.DataFrame):
            self.labels = csv_file
        elif isinstance(csv_file, str):
            self.labels = pd.read_csv(csv_file)
        self.root_dir = root_dir
        self.transform = transform

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        if torch.is_tensor(idx):
            idx = idx.tolist()

        anchor_path = os.path.join(self.root_dir,               # Directory to all ant folders
                                self.labels.iloc[idx, 0],       # Directory to specific ant folder
                                self.labels.iloc[idx, 1])       # Filename of anchor image

        anchor_image = Image.open(anchor_path)

        if self.transform:
            anchor_image = self.transform(anchor_image)

        # Get ant id number
        ant_id = torch.tensor(int(self.labels.iloc[idx, 0].split("_")[-1]))
        return anchor_image, (self.labels.iloc[idx, 0])


# -*- coding: utf-8 -*-
import os

"""
    1. --parallel-mode：使Coverage监测被测代码子进程的覆盖率，如果被测代码是多进程的，必须使用此参数；
    2. --branch：统计分支代码覆盖率，加上这个参数可使统计更精确,
         branch=True 选项开启分支覆盖分析
    3.--include: 限定要统计代码的路径，如果不限定，Coverage会把请求涉及到的所有代码，
                 包括系统库和Tornado框架的代码都分析一遍，会大大拉低代码覆盖率；
        include 选项用来限制程序包中文件的分析范围，只对这些文件中的代码进行覆盖 检测。
"""
COV = None
if os.environ.get('FLASK_COVERAGE'):
    import coverage
    # 启动覆盖检测引擎
    COV = coverage.coverage(branch=True, include='app/*')
    COV.start()

from app import create_app, db
from app.models import User, Role
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

env = os.getenv('FLASK_CONFIG') or 'default'
app = create_app(env)
manager = Manager(app)
migrate = Migrate(app, db)

def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

@manager.command
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'tmp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()

if __name__ == '__main__':
    manager.run()


"""JobRecommend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from calc import views as calc_views
from zhilianjob import views as job_views

urlpatterns = [
    path('', job_views.index, name="index"),

    path('posin/', job_views.posin, name="posin"),
    path('workn/', job_views.workn, name="workn"),
    path('compn/', job_views.compn, name="compn"),
    path('sizen/', job_views.sizen, name="sizen"),
    path('attributen/', job_views.attributen, name="attributen"),
    path('fieldn/', job_views.fieldn, name="fieldn"),
    path('workedun/', job_views.workedun, name="workedun"),
    path('edusaln/', job_views.edusaln, name="edusaln"),
    path('expsaln/', job_views.expsaln, name="expsaln"),

    path('upload/', job_views.upload, name='upload'),
    path('result/', job_views.result, name='result'),

    path('test/', job_views.test, name="test"),
    path('new_add/<int:a>/<int:b>/', calc_views.add2, name='add2'),
    path('add/', calc_views.add, name='add'),

    path('admin/', admin.site.urls),
]


import torch.nn as nn
import numpy as np
import torch
from pathlib2 import Path
from .denseunet import DenseUNet
from .dataset.kit import KitDataset
from .dataset.transform import MedicalTransform
from .checkpoint import load_params
from torch.utils.data import DataLoader, SequentialSampler

class Eval:

    def __init__(self, bach_size, img_size, data_path, resume):
        self._batch_size = bach_size
        self._img_size = img_size
        self._data_path = Path(data_path)
        self._resume = Path(resume)
        self._dataset = KitDataset(data_path, stack_num=3, img_size=img_size, transform=MedicalTransform(img_size))
        self._net = DenseUNet(in_ch=self._dataset.stack_num, out_ch=self._dataset.img_channels)
        self._sampler = SequentialSampler(self._dataset)
        self._data_loader = DataLoader(self._dataset, batch_size=self._batch_size, sampler=self._sampler, num_workers=1, pin_memory=True)
        self.load_params()

    def load_params(self):

        assert self._resume.exists()
        data = {'net': self.net}
        load_params(data, self._resume)
        print(f'{" Start evaluation ":-^40s}\n')
        msg = f'Net: {self._net.__class__.__name__}\n' + \
            f'Batch size: {self._batch_size}\n'
        print(msg)
        self._net.eval()
        torch.set_grad_enabled(False)

    def __call__(self):
        for batch_idx, data in enumerate(self._data_loader):
            imgs = data['image'].cpu()
            outputs = self._net(imgs)
            predicts = outputs['output']
            predicts = predicts.argmax(dim=1)
            predicts = predicts.cpu().detach().numpy()
            data['predict'] = predicts
            yield data

    @property
    def dataset(self):
        return self._dataset

    @property
    def img_size(self):
        return self._img_size

    @property
    def net(self):
        return self._net

if __name__ == '__main__':
    e = Eval(3, 512, './dataset/data/0/imaging/', './best.pth')
    for data in e():
        print(data['predict'].shape)


from photo_searcher import app
#File_helperをfileとしてimport
from photo_searcher.helpers.file_helper import file_get_contents

import random  # デバッグ用
import os
import re
import glob
import execjs

#views.search()で必要なデータを返す
def set_show_data(keyword):
    # rows = file_get_contents('photo_searcher/static/img_list.txt')[:100]
    if len(keyword) > 0:
        rows = search_img_data(keyword)
    else:
        rows = []

    row_cnt = len(rows)

    return rows, row_cnt

#キーワードに見合う画像の検索
def search_img_data(keyword):
    #先頭または末尾のの不要なスペースを削除
    keyword = keyword.replace('\u3000', ' ')
    keyword = keyword.replace('  ', ' ')
    while True:
        if keyword[:1] == ' ':
            keyword = keyword[1:]
        elif keyword[-1:] == ' ':
            keyword = keyword[:-1]
        else:
            break
    sp_or = keyword.split(' OR ') #ORで区切る
    res_use = []
    for el in sp_or:
        #AND検索
        sp_and = el.split(' ')
        tmp_and_use = []
        tmp_and_unuse = []
        for el2 in sp_and:
            pathes = []
            if(re.sub("\\D", "", el2)):
                num = re.sub("\\D", "", el2)
                    #数字のみ後方一致
                pathes = glob.glob('photo_searcher/static/data_store/fc/' + num + '.keyword')
                tmp_array = [add_key_num(path) for path in pathes]
                if tmp_array:
                    s = set(tmp_array[0])
                    for t in tmp_array:
                        s |= set(t)
                    tmp_and_use.append(list(s))
            elif el2[0] == '-':
                pathes = glob.glob('photo_searcher/static/data_store/tf/' + el2[1:] + '.keyword')
                tmp_array = [add_key_words(path) for path in pathes]
                if tmp_array:
                    s = set(tmp_array[0])
                    for t in tmp_array:
                        s |= set(t)
                    tmp_and_unuse.extend(list(s))
            else:
                pathes = glob.glob('photo_searcher/static/data_store/tf/*' + el2 + '*.keyword')
                tmp_array = [add_key_words(path) for path in pathes]
                if tmp_array:
                    s = set(tmp_array[0])
                    for t in tmp_array:
                        s |= set(t)
                    tmp_and_use.append(list(s))
        #キーワードに関する配列毎に共通項を抽出
        if len(tmp_and_use) > 0:
            tmp = set(tmp_and_use[0])
            for el3 in tmp_and_use:
                tmp &= set(el3)
            # tmp = list(tmp)
            res_use.extend(list(tmp))
        if len(tmp_and_unuse) > 0:
            for el in tmp_and_unuse:
                if el in res_use:
                    res_use.remove(el)
    return list(set(res_use))

#使用するワードをリストに追加
#キーワードに関する画像データを返す
def add_key_words(path):
    response = []
    if len(response) > 0:
        response.clear()
    if os.path.exists(path) and os.path.isfile(path):
        with open(path, 'r') as r:
            for line in r:
                img_path = line.split('\t')[2].replace('\n','')
                response.append(img_path[2:])  #「..」を削除する
    return response

def add_key_num(path):
    response = []
    if len(response) > 0:
        response.clear()
    if os.path.exists(path) and os.path.isfile(path):
        with open(path, 'r') as r:
            for line in r:
                img_path = line.split('\t')[1].replace('\n','')
                response.append(img_path[2:])  #「..」を削除する
    return response

#jsのlocalStorageを参照して画面テーマを取得
def get_theme():
    ctx = execjs.compile("""
        function getTheme() {
            if(localStorage.getItem('theme')) {
                return localStorage.getItem('theme');
                // if(localStorage.getItem('theme') == 'dark') {
                //     return 'rgb(25, 25, 25)';
                // }else{
                //     return 'rgb(250, 250, 250)';
                // }
            }else{
                // return 'rgb(250, 250, 250)';
                return 'light';
            }
        }
    """)
    return ctx.call('getTheme')


import numpy as np
from math import erf
from matplotlib import pyplot as plt

xo = 0.5

N = 100000
dtheta = 0.2
dx = 0.1

# Theta values to test. Theta corresponds to pop. mean.
theta1s = np.arange(-1, 1 + dtheta, dtheta)
theta2s = np.arange(dtheta, 1 + dtheta, dtheta)

# bin edges
binsx = np.arange(-5, 5 + dx, dx)
# bin centers
binsxc = binsx[0:-1] + dx/2

d = (theta1s.size, theta2s.size)
P_D_theta = np.full(d, np.nan)
P_D_theta_exactish = np.full(d, np.nan)

for i in range(theta1s.size):
    for j in range(theta2s.size):
        x = np.random.normal(theta1s[i], theta2s[j], size=N)
        n, _ = np.histogram(x, bins=binsx)

        idx = np.where(np.abs(binsxc - xo) <= dx/2)[0]
        if (idx.size > 1):
            print('xo is on boundary of two bins.')
            idx = idx[0]

        P_D_theta[i,j] = n[idx]/N

        print('P = {0:.2f}; theta1 = {1:.2f}; theta2 = {2:.2f}'.format(P_D_theta[i,j],theta1s[i],theta2s[j]))

        P_D_theta_exactish[i,j] = dx*np.exp( -(xo-theta1s[i])**2/(2.0*theta2s[j]**2) )/np.sqrt(2*np.pi*theta2s[j]**2)

print("sum(P_D_theta_exactish) on grid: {0:.4f}".format(np.sum(P_D_theta_exactish)))

P_theta_D_exactish = P_D_theta_exactish/np.sum(P_D_theta_exactish)
P_theta_D = P_D_theta/np.sum(P_D_theta)

theta1se = np.append(theta1s, theta1s[-1] + dtheta)
theta1se = theta1se - dtheta/2

theta2se = np.append(theta2s, theta2s[-1] + dtheta)
theta2se = theta2se - dtheta/2

plt.figure(1)
m = plt.pcolor(theta1se, theta2se, P_theta_D.T, cmap=plt.get_cmap('viridis', 20))
m.set_clim(0,0.1)
cb = plt.colorbar(m)
plt.ylabel('$\\theta_2$')
plt.xlabel('$\\theta_1$')
cb.ax.set_title('$P([\\theta_1,\\theta_2]|\mathcal{D})$')
plt.title('Simulation')

# Set ticks to match centers
plt.xticks(theta1s)
plt.yticks(theta2s)

plt.figure(2)
m = plt.pcolor(theta1se, theta2se, P_theta_D_exactish.T, cmap=plt.get_cmap('viridis', 20))
m.set_clim(0,0.1)
cb = plt.colorbar(m)
plt.ylabel('$\\theta_2$')
plt.xlabel('$\\theta_1$')
cb.ax.set_title('$P([\\theta_1,\\theta_2]|\mathcal{D})$')
plt.title('Exactish')

# Set ticks to match centers
plt.xticks(theta1s)
plt.yticks(theta2s)

P_delta = P_theta_D -P_theta_D_exactish
plt.figure(3)
m = plt.pcolor(theta1se, theta2se, P_delta.T, cmap=plt.get_cmap('viridis', 20))
m.set_clim(-0.1,0.1)
cb = plt.colorbar(m)
plt.ylabel('$\\theta_2$')
plt.xlabel('$\\theta_1$')
plt.title('Simulation-Exactish using same color scale')

# Set ticks to match centers
plt.xticks(theta1s)
plt.yticks(theta2s)


#제목: 터렛
"""
이석원은 조규현과 백승환에게 상대편 마린(류재명)의 위치를 계산하라는 명령을 내렸다. 조규현과 백승환은 각각 자신의 터렛 위치에서 현재 적까지의 거리를 계산했다.

조규현의 좌표 (x1, y1)와 백승환의 좌표 (x2, y2)가 주어지고, 조규현이 계산한 류재명과의 거리 r1과 백승환이 계산한 류재명과의 거리 r2가 주어졌을 때, 류재명이 있을 수 있는 좌표의 수를 출력하는 프로그램을 작성하시오.
"""

import math

# 3
T = int(input("값입력: "))

# 0 0 13 40 0 37
# 0 0 3 0 7 4
# 1 1 1 1 1 5
for _ in range(T):
    x1, y1, r1, x2, y2, r2 = map(int, input("입력: ").split())
    distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

    if x1 == x2 and y1 == y2:
        if r1 == r2:
            print(-1)
        else:
            print(0)

    else:
        if r1 > distance + r2 or r2 > distance + r1 or distance > r1 + r2:
            print(0)
        elif abs(r1 - r2) == distance or r1 + r2 == distance:
            print(1)
        else:
            print(2)


from django.shortcuts import render
from .models import Categories, Playlists
import pytube

##################
# 1. Categories
##################
def home(request):
    '''
    Displays all the categories in the home page
    '''
    cat_obj = Categories.objects.all()
    context = {
        'cat_obj': cat_obj,
    }
    return render(request, "back/index.html", context)

# Get the title of the playlist
def get_title(url):
    playlist_obj = pytube.Playlist(url=url)
    title = playlist_obj.title
    # channelName = playlist_obj.owner
    return title

###############################
# 2. Category wise playlists
###############################
def categories(request, id):
    '''
    This function returns all the playlists with a specific category
    data is from the model
    '''
    playlists = Playlists.objects.filter(category=id)
    code_list = []
    for index in range(len(playlists)):
        code_list.append(str(playlists[index].url).split("=")[1])
    context = {
        'code_list': code_list,
    }
    return render(request, "back/categories.html", context)

################################################
# 3. Playlists wise (All videos in playlist)
################################################
def list_url(request, code):
    '''
    This function returns all the video urls in a playlist
    '''
    url = "https://www.youtube.com/playlist?list=" + code
    playlist_obj = pytube.Playlist(url=url)
    vid_url = playlist_obj.videos
    vid_urls = []
    for index in vid_url:
        urls = index.streams.filter(progressive="True").filter(res="720p")[0]
        vid_urls.append(urls)
    return render(request, "back/list.html", context={'vid_urls': vid_urls})

# 4. Detail (Video click urls)


# Softeer level3 성적평균.py

# N: 학생 수, K: 구간 수
N, K = map(int, input().split())

# 학생들의 점수를 저장
scores = list(map(int, input().split()))

# 평균을 저장할 빈 list
averages = []
for i in range(K):
    start, end = map(int, input().split())

    tmp_sum = 0
    for k in range(start - 1, end):
        tmp_sum += scores[k]

    tmp_sum /= end - start + 1
    averages.append(format(tmp_sum, '.2f'))

for average in averages:
    print(average)

#다른 풀이도 있다.
# import sys
#
# #N, K를 받는 것
# N, K = map(int, input().split())
#
# #점수들을 받아서 list에 저장
# score = list(map(int, sys.stdin.readline().split()))
#
# #출력할 범위 들을 받아서 list안에 list로 형성
# range_list = [list(map(int, sys.stdin.readline().split())) for _ in range(K) ]
#
# #범위 별로 출력
# for i in range(K):
#     cut_score = score[range_list[i][0]-1:range_list[i][1]]
#     result = sum((cut_score))/len(cut_score)
#     result = format(result, '.2f')
#     print(result)


def selectionSort(array: list) -> list:
	for i in range(len(array) - 1):
		minIndex = i
		for j in range(i + 1, len(array)):
			if array[j] < array[minIndex]:
				minIndex = j
		array[i], array[minIndex] = array[minIndex], array[i]

def recursiveSelectionSort(array: list) -> list:
	if len(array) > 1:
		minIndex = 0
		for index in range(1, len(array)):
			if array[index] < array[minIndex]:
				minIndex = index
		array[0], array[minIndex] = array[minIndex], array[0]
		array = array[:1] + recursiveSelectionSort(array[1:])
	return array

if __name__ == '__main__':
	# array = random.sample(range(1, 1000), 500)
	array = [5, 3, 2, 10 , 1 , 9]
	selectionSort(array)
	print(array)
	print(recursiveSelectionSort(array))


import requests
import config
from db_mysql import DB_operating
from lxml import html
import uuid
from AipOcr import aip
from file import makidir
from PIL import Image
DB = DB_operating()
makidir=makidir()
aip=aip()
class spiderclass(object):
    def __init__(self):
        super().__init__()

    # 爬取网页
    def spider(self, url):
        try:
            html = requests.get(url, headers=config.headers)
            html.encoding = 'utf-8'
            return html.text
        except Exception as e:
            print(e, '该URL抓取失败',url)
            html.close()
            return ''
    def spider_xpath(self, htmls, xpath,url,imgtype):
        tree = html.fromstring(htmls)
        contexts = tree.xpath(xpath)
        context = ''
        for item in contexts:
            self.download_image(item,url,imgtype)
    def download_image(self, imgurl,url,imgtype):
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
                   'Referer': url,
                   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                   'Accept-Encoding': 'gzip, deflate, sdch',
                   'Accept-Language': 'zh-CN,zh;q=0.8',
                   'Cache-Control': 'max-age=0',
                   'Connection': 'keep-alive',
                   }
        if 'http:' in imgurl:
            img = requests.get(imgurl, stream=True, headers=headers)
            filename = imgurl.split('/')[-1]
            # D:\python_download_img
            with open(config.filepath+"/" + filename, 'wb') as f:
                for chunk in img.iter_content(chunk_size=1024):
                    if chunk:  # filter out keep-alive new chunks
                        f.write(chunk)
                        f.flush()
                f.close()
            path=config.filepath.split("/")[-1]+'/'+filename
            #PIL模块改变图片大小 哈哈
            filepath=config.filepath+'/'+filename
            try:
                makidir.UpdateImageSize(filepath)
                # 图像识别
                res = aip.aipOcrGeneral(filepath)
                words=''
                for dome in res['words_result']:
                    words+=dome['words']
                DB.INSERT_imgpath(filename, path, imgtype,words)
            except Exception as e:
                print(e)
            print('爬取图片:', filename)


import os
from threading import Thread
from subprocess import Popen, PIPE
from select import select
from multiprocessing import Queue

class job:
    def __init__(self, p, q):
        self.p = p
        self.q = q

    def p(self):
        return p

    def q(self):
        return q

class Runner:
    """
    This class provides the container interface for Docker.

    """

    def __init__(self):
        """
        Inputs: config dictionary, Job ID, and optional logger
        """
        self.procs = []
        self.threads = []

    def _readio(self, p, q):
        cont = True
        last = False
        while cont:
            rlist = [p.stdout, p.stderr]
            x = select(rlist, [], [], 1)[0]
            for f in x:
                if f == p.stderr:
                    error = True
                else:
                    error = False
                line = f.readline().decode('utf-8')
                if len(line) > 0:
                    q.put({'msg': 'output', 'line': line, 'error': error})
            if last:
                cont = False
            if p.poll() is not None:
                last = True
        q.put({'msg': 'finished', 'exit': p.returncode})

    def run(self, cmd):
        q = Queue()
        proc = Popen(cmd, bufsize=0, stdout=PIPE, stderr=PIPE)
        out = Thread(target=self._readio, args=[proc, q])
        self.threads.append(out)
        out.start()
        self.procs.append(proc)
        return job(proc, q)


import numpy as np
import dask.array as da

from hyperspy.component import _get_scaling_factor
from hyperspy._components.expression import Expression
from hyperspy.misc.utils import is_binned # remove in v2.0

def _estimate_lorentzian_parameters(signal, x1, x2, only_current):
    axis = signal.axes_manager.signal_axes[0]
    i1, i2 = axis.value_range_to_indices(x1, x2)
    X = axis.axis[i1:i2]

    if only_current is True:
        data = signal()[i1:i2]
        i = 0
        centre_shape = (1,)
    else:
        i = axis.index_in_array
        data_gi = [slice(None), ] * len(signal.data.shape)
        data_gi[axis.index_in_array] = slice(i1, i2)
        data = signal.data[tuple(data_gi)]
        centre_shape = list(data.shape)
        centre_shape[i] = 1

    cdf = np.cumsum(data,i)
    cdfnorm = cdf/np.max(cdf, i).reshape(centre_shape)

    icentre = np.argmin(abs(0.5 - cdfnorm), i)
    igamma1 = np.argmin(abs(0.75 - cdfnorm), i)
    igamma2 = np.argmin(abs(0.25 - cdfnorm), i)

    if isinstance(data, da.Array):
        icentre, igamma1, igamma2 = da.compute(icentre, igamma1, igamma2)

    centre = X[icentre]
    gamma = (X[igamma1] - X[igamma2]) / 2
    height = data.max(i)

    return centre, height, gamma

class Lorentzian(Expression):

    r"""Cauchy-Lorentz distribution (a.k.a. Lorentzian function) component.

    .. math::

        f(x)=\frac{A}{\pi}\left[\frac{\gamma}{\left(x-x_{0}\right)^{2}
            +\gamma^{2}}\right]

    ============== =============
    Variable        Parameter
    ============== =============
    :math:`A`       A
    :math:`\gamma`  gamma
    :math:`x_0`     centre
    ============== =============

    Parameters
    -----------
    A : float
        Area parameter, where :math:`A/(\gamma\pi)` is the maximum (height) of
        peak.
    gamma : float
        Scale parameter corresponding to the half-width-at-half-maximum of the
        peak, which corresponds to the interquartile spread.
    centre : float
        Location of the peak maximum.
    **kwargs
        Extra keyword arguments are passed to the
        :py:class:`~._components.expression.Expression` component.

    For convenience the `fwhm` and `height` attributes can be used to get and set
    the full-with-half-maximum and height of the distribution, respectively.
    """

    def __init__(self, A=1., gamma=1., centre=0., module="numexpr", **kwargs):
        # We use `_gamma` internally to workaround the use of the `gamma`
        # function in sympy
        super().__init__(
            expression="A / pi * (gamma_ / ((x - centre)**2 + gamma_**2))",
            name="Lorentzian",
            A=A,
            gamma=gamma,
            centre=centre,
            position="centre",
            module=module,
            autodoc=False,
            rename_pars={"gamma_": "gamma"},
            **kwargs)

        # Boundaries
        self.A.bmin = 0.
        self.A.bmax = None

        self.gamma.bmin = None
        self.gamma.bmax = None

        self.isbackground = False
        self.convolved = True

    def estimate_parameters(self, signal, x1, x2, only_current=False):
        """Estimate the Lorentzian by calculating the median (centre) and half
        the interquartile range (gamma).

        Note that an insufficient range will affect the accuracy of this
        method.

        Parameters
        ----------
        signal : Signal1D instance
        x1 : float
            Defines the left limit of the spectral range to use for the
            estimation.
        x2 : float
            Defines the right limit of the spectral range to use for the
            estimation.

        only_current : bool
            If False estimates the parameters for the full dataset.

        Returns
        -------
        bool

        Notes
        -----
        Adapted from gaussian.py and
        https://en.wikipedia.org/wiki/Cauchy_distribution

        Examples
        --------

        >>> g = hs.model.components1D.Lorentzian()
        >>> x = np.arange(-10, 10, 0.01)
        >>> data = np.zeros((32, 32, 2000))
        >>> data[:] = g.function(x).reshape((1, 1, 2000))
        >>> s = hs.signals.Signal1D(data)
        >>> s.axes_manager[-1].offset = -10
        >>> s.axes_manager[-1].scale = 0.01
        >>> g.estimate_parameters(s, -10, 10, False)
        """

        super()._estimate_parameters(signal)
        axis = signal.axes_manager.signal_axes[0]
        centre, height, gamma = _estimate_lorentzian_parameters(signal, x1, x2,
                                                              only_current)
        scaling_factor = _get_scaling_factor(signal, axis, centre)

        if only_current is True:
            self.centre.value = centre
            self.gamma.value = gamma
            self.A.value = height * gamma * np.pi
            if is_binned(signal):
            # in v2 replace by
            #if axis.is_binned:
                self.A.value /= scaling_factor
            return True
        else:
            if self.A.map is None:
                self._create_arrays()
            self.A.map['values'][:] = height * gamma * np.pi
            if is_binned(signal):
            # in v2 replace by
            #if axis.is_binned:
                self.A.map['values'] /= scaling_factor
            self.A.map['is_set'][:] = True
            self.gamma.map['values'][:] = gamma
            self.gamma.map['is_set'][:] = True
            self.centre.map['values'][:] = centre
            self.centre.map['is_set'][:] = True
            self.fetch_stored_values()
            return True

    @property
    def fwhm(self):
        return self.gamma.value * 2

    @fwhm.setter
    def fwhm(self, value):
        self.gamma.value = value / 2

    @property
    def height(self):
        return self.A.value / (self.gamma.value * np.pi)

    @height.setter
    def height(self, value):
        self.A.value = value * self.gamma.value * np.pi


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# from http://zetcode.com/gui/pyqt5/

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Example(QWidget):
    def __init__(self):
        super(QWidget, self).__init__()
        self.initUI()

    def initUI(self):

        title = QLabel('Title')
        author = QLabel('Author')
        review = QLabel('Review')

        titleEdit = QLineEdit()
        authorEdit = QLineEdit()
        reviewEdit = QTextEdit()

        grid = QGridLayout()
        grid.setSpacing(10)

        grid.addWidget(title, 1, 0)
        grid.addWidget(titleEdit, 1, 1)

        grid.addWidget(author, 2, 0)
        grid.addWidget(authorEdit, 2, 1)

        grid.addWidget(review, 3, 0, Qt.AlignTop)
        grid.addWidget(reviewEdit, 3, 1, 5, 1)  # span 5 rows and 1 col

        self.setLayout(grid)

        self.setGeometry(300, 300, 350, 300)
        self.setWindowTitle('Review')
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


import sys, os
sys.path.insert(1, os.path.join(sys.path[0], '..'))

from utility import bloom_filter, query_contact, upload_contact
from pprint import pprint

bf = bloom_filter(800000, 3, 1000)
bf.put("amazing")
bf.put("great")

result = query_contact(bf, 'http://ec2-3-26-37-172.ap-southeast-2.compute.amazonaws.com:9000/comp4337/qbf/query')
pprint(result)
if result.find("No Match"):
    print("result: None Match!")
result = upload_contact(bf, 'http://ec2-3-26-37-172.ap-southeast-2.compute.amazonaws.com:9000/comp4337/cbf/upload')
pprint(result)

result = query_contact(bf, 'http://ec2-3-26-37-172.ap-southeast-2.compute.amazonaws.com:9000/comp4337/cbf/query')
pprint(result)


from collections import OrderedDict

class DicMasques(OrderedDict):

    """Dictionnaire ordonné contenant les masques."""

    def __str__(self):
        """Affichage plus propre des masques."""
        msgs = []
        for masque in self.values():
            if hasattr(masque, "nom_francais"):
                msg = masque.nom_francais
            else:
                msg = repr(masque.a_interpreter)
            msgs.append(msg)

        return " ".join(msgs)

    def __getitem__(self, item):
        """Retourne l'item si présent ou None sinon"""
        if item not in self:
            res = None
        else:
            res = OrderedDict.__getitem__(self, item)

        return res

    @property
    def premier(self):
        """Retourne le premier élément du dictionnaire"""
        return tuple(self.values())[0]

    @property
    def dernier(self):
        """Retourne le dernier élément du dictionnaire"""
        return tuple(self.values())[-1]

    @property
    def dernier_parametre(self):
        """Retourne le dernier paramètre"""
        for masque in reversed(list(self.values())):
            if masque.est_parametre():
                return masque

        raise ValueError("aucun paramètre dans ce dictionnaire")


import django.contrib.postgres.fields as postgres_fields
from django.db import models
from django.utils.translation import gettext_lazy as _

class Post(models.Model):
    class SourceName(models.TextChoices):
        HABR = 'habr'
        MEDIUM = 'medium'
        DCM = 'distributed_computing_musings'

    canonized_url = models.CharField(max_length=2048, db_index=True)
    source_name = models.CharField(max_length=128, choices=SourceName.choices)
    original_url = models.CharField(max_length=2048)
    title = models.CharField(max_length=256)
    topics = postgres_fields.ArrayField(models.CharField(max_length=256), db_index=True)
    rank = models.BigIntegerField()
    starting_text = models.TextField()
    publish_timestamp = models.BigIntegerField()
    author_username = models.CharField(max_length=128, blank=True, null=True)
    views = models.BigIntegerField(blank=True, null=True)

    def __str__(self) -> str:
        return f'Post({self.id}, canonized_url={self.canonized_url})'

    @staticmethod
    def example() -> 'Post':
        from django.utils import timezone
        return Post(
            canonized_url='https://test.com/path',
            source_name='habr',
            original_url='https://test.com/path?flag=true',
            title='MyTitle',
            topics=['development'],
            rank=1,
            starting_text='my text',
            publish_timestamp=int(timezone.now().timestamp()),
            author_username='admin',
            views=0,
        )


# Write a program that asks the user for a number n and gives them the
# possibility to choose between computing the sum and computing the product of 1,…,n.

def getSum(number):
    return (number * (number + 1)) / 2

def getProduct(number):
    product = 1
    for i in range(1, number+1):
        product *= i
    return product

try:
    input_number = int(input("Enter number : "))
    choice = input("Compute sum or product : ")
    print(choice)
    if choice == "sum":
        print(f"Sum of number till n is {getSum(input_number)}")
    elif choice == "product":
        print(f"Product of number till n is {getProduct(input_number)}")

except:
    print("Enter correct input")


from io import open
import pickle

class Pelicula:
    #Constructor de clase
    def __init__(self,titulo,duración,lanzamiento):
        self.titulo = titulo
        self.duración = duración
        self.lanzamiento = lanzamiento
        print("Se ha creado la película: ",self.titulo)

    def __str__(self):
        return '{} ({})'.format(self.titulo, self.lanzamiento)

class Catalogo:

    peliculas = []

    #Constructor de clase
    def __init__(self):
        #Aquí vamos a cargar las pelícuals del fichero
        self.cargar()

    def agregar(self,p):
        self.peliculas.append(p)
        self.guardar() #añadiendo aquí guardar cada vez que agreguemos una peli se guardará

    def mostrar(self):
        if len(self.peliculas) == 0:
            print("El catálogo está vacío")
            return
        for p in self.peliculas:
            print(p)
        #Aquí tenemos nuestro catálogo de películas y ahora lo que vamos a hacer es guardar y cargar los datos dentro de un fichero
        #Para que no se borre nuestro catálogo cada vez que lo cerramos
    def cargar(self):#Esto cargará el contenido del fichero
        fichero = open('catálogo.pckl','ab+')#Append binario con + que indica lectura
        fichero.seek(0) #Debido al modo append el puntero se iniciará siempre al final y no podremos leer. Por eso recolocamos el puntero
        try:
            self.peliculas = pickle.load(fichero)
            #Debido a que la primera vez no va a existir el fichero dará el error y entonces se implementará desde el except
        except:
            print("El fichero está vacío")
        finally:
            fichero.close()#Cerramos siemrpe el fichero
            print("Se han cargado {} películas".format(len(self.peliculas)))
    def guardar(self):#Esto guardará el contenido del fichero
        #Aquí vamos a abrir el fichero en escritura binaria eliminando los datos, añadiendo los nuevos y volcando de nuevo el fichero
        fichero = open('catálogo.pckl','wb')
        pickle.dump(self.peliculas, fichero)#volcamos la lista de peliculas en el fichero
        fichero.close()
        #La siguiente función de la clase es una prueba, aún debe realizarse
    def eliminar(self,pelicula_eliminada): #NO FUNCIONA
        if pelicula_eliminada in self.peliculas:
            self.peliculas.remove(pelicula_eliminada)
            print("La película {} ha sido eliminada".format(pelicula_eliminada))
            self.guardar()
        else:
            print("Esa película no está en el catálogo")
    #Destructor de clase
    def __del__(self):
        self.guardar() #Esto guardaría automáticamente los datos en caso de que cerremos el programa sin guardar previamente
        print("Se ha guardado el fichero")

# c = Catalogo()
# c.agregar(Pelicula("El padrino",175,1972))
# c.agregar(Pelicula("El Padrino II",202,1974))
# c.mostrar()
# del(c)
# c.agregar (Pelicula ("regueton duro", 123, 1987))
#(Debemos tener cuidado al ejecutar estos comandos porque el código es recursivo, es decir
# si ejecutamos el código varias veces pueden ocurrir errores ya que la información se ha guardado y no se borra con el código sino cuando eliminamos el archivo)
c = Catalogo()
c.agregar(Pelicula("El padrino",175,1972))
c.agregar(Pelicula("El Padrino II",202,1974))
c.eliminar("El padrino")
c.mostrar()


"""
X requires a loss       A=Rock    1 Point       Beaten by Paper
Y requires a draw       B=Paper   2 Point      Beaten by Scissors
Z requires a win        C=Scissors 3 Point      Beaten by Rock

"""
# Create a function to determine the score
def winner(opponent):
    if opponent == 'A': #Paper beats rock
        return 8
    elif opponent == 'B': #Scissors beat paper
        return 9
    elif opponent == 'C': #Rock beats scissors
        return 7

def drawn(opponent):
    if opponent == 'A':
        return 4
    if opponent == 'B':
        return 5
    if opponent == 'C':
        return 6

def loss(opponent):
    if opponent == 'A':
        return 3
    if opponent == 'B':
        return 1
    if opponent == 'C':
        return 2

data = []
for line in open("strat.txt", "r"):
    split = line.strip().split(' ')
    O = split[0]
    M = split[1]

    if M == 'X':
        data.append(loss(O))
    elif M == 'Y':
        data.append(drawn(O))
    elif M == 'Z':
        data.append(winner(O))

print(sum(data))


import discord
import json
import os
import re
import datetime
import traceback
import random
import sys
import asyncio
from discord.ext import commands
from pip._vendor import requests
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

class Mod(commands.Cog):

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

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.content.startswith("@everyone") and message.author.id == 759126142875074580:
            await message.channel.send("Powering off, everyone or here ping exploit.")
            sys.exit()
        elif message.content.startswith("@here") and message.author.id == 7591261428750745801:
            await message.channel.send("Powering off, everyone or here ping exploit.")
            sys.exit()

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def lock(self,ctx, amount = 1):
        await ctx.channel.purge(limit = amount)
        await ctx.message.channel.set_permissions(ctx.guild.default_role, send_messages=False)
        embed = discord.Embed(title = 'This channel has been locked by: ' + str(ctx.message.author))
        await ctx.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages = True)
    async def nick(self,ctx,member:discord.Member,*,name = None):
        if name == None:
            await member.edit(nick = ctx.author)
        await member.edit(nick = name)
        embed = discord.Embed(title = 'Nick Name Successfully Changed!')
        await ctx.send(embed = embed)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def unlock(self,ctx, amount = 1):
        await ctx.channel.purge(limit = amount)
        await ctx.message.channel.set_permissions(ctx.guild.default_role, send_messages=True)
        embed = discord.Embed(title = 'This channel has been unlocked by: ' + str(ctx.message.author))
        await ctx.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_channels = True)
    async def slowmode(self,ctx,time:int):
        try:
            if time == 0:
                embed = discord.Embed(title = 'Slowmode turned off')
                await ctx.send(embed = embed)
                await ctx.channel.edit(slowmode_delay = 0)
            elif time > 21600:
                embed = discord.Embed(title = 'You cannot have a slowmode above 6hrs.')
                await ctx.send(embed = embed)
            else:
                await ctx.channel.edit(slowmode_delay = time)
                embed = discord.Embed(title = f'Slowmode set to {time} seconds.')
                await ctx.send(embed = embed)
        except Exception:
            traceback.print_exc()

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def softban(self,ctx, member:discord.Member,*, reason = 'No reason provided'):
        await member.ban(reason = reason)
        await member.unban(reason = reason)
        embed = discord.Embed(title = f'Successfully softbanned {member}')
        await ctx.send(embed = embed)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def tempban(self,ctx,member:discord.Member,time,*,reason = 'No Reason Provided'):
        with open('guild.json','r') as f:
            channels = json.load(f)
        indicator = time[-1]
        if indicator == "m" or indicator == "s" or indicator == 'h' or indicator == 'd':
            pass
        else:
            await ctx.send('Incorrect Time Format.')
        embed = discord.Embed(title = f'{member} has been temp banned for {time}.')
        await ctx.send(embed = embed)
        await member.ban(reason = reason)
        chanid = channels[str(ctx.guild.id)]['admin'][0]['adid']
        channel = self.bot.get_channel(chanid)
        embed = discord.Embed(title = 'Member Tempbanned!', color = discord.Colour.red())
        embed.add_field(name = f'{member} was tempbanned({time}) from {ctx.guild.name} for: ',value = f'{reason}')
        await channel.send(embed = embed)
        time = time[:-1]
        if indicator == 'm':
            await asyncio.sleep(int(time) * 60)
        elif indicator == 'h':
            await asyncio.sleep(int(time) * 3600)
        elif indicator == 's':
            await asyncio.sleep(int(time))
        elif indicator == 'd':
            await asyncio.sleep(int(time) * 86400)
        await member.unban(reason = 'Timer has expired.')

    '''@commands.command()
    async def selfmute(self,ctx,time):
        try:
            orig_time = time
            embed = discord.Embed(title = f"Are you sure you want to mute yourself?", description =  f"Reacting will seriously mute you for {time}.\n If this is a mistake just do not react and wait for it to time out in 30 seconds.")
            msg = await ctx.send(embed = embed)
            def reactionchk(reaction,x):
                return x.id == ctx.author.id and str(reaction.emoji) == "👍"

            try:
                await msg.add_reaction("👍")
                await self.bot.wait_for('reaction_add', timeout = 30, check = reactionchk)
            except asyncio.TimeoutError:
                await ctx.send('Timeout Error, Aborting.')
            indicator = time[-1]
            if indicator == "m" or indicator == "s" or indicator == 'h':
                pass

            time = time[:-1]
            time = int(time)
            if time * 3600 > 21600 and indicator == 'h' or time * 60 > 21600 and indicator == 'm' or time > 21600 and indicator == 's':
                embed = discord.Embed(title = "We cannot mute you for more than 6 hours.")
                await ctx.send(embed = embed)
                return
            muted = discord.utils.get(ctx.guild.roles, name = 'Muted')
            await ctx.author.add_roles(muted)
            embed = discord.Embed(title = f'Successfully muted you for {orig_time}.')
            await ctx.send(embed = embed)
            if indicator == 'm':
                await asyncio.sleep(int(time) * 60)
            elif indicator == 'h':
                await asyncio.sleep(int(time) * 3600)
            elif indicator == 's':
                await asyncio.sleep(int(time))
            await ctx.author.remove_roles(muted)
        except Exception:
            traceback.print_exc()'''

    @commands.command(aliases = ['purge'])
    @commands.has_permissions(manage_messages=True)
    async def clear(self,ctx,amount:int = 5):
        await ctx.channel.purge(limit=amount)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def ban(self, ctx, member : discord.Member=None, *, reason = None):
        if member == ctx.author:
            await ctx.send("Oi you can't ban yourself.")
            return
        if member is None:
            em = discord.Embed(title = 'Please specify a member.')
            await ctx.send(embed = em)
            return
        await member.ban(reason = reason)
        em = discord.Embed(title = f'You banned {member}')
        await ctx.send(embed = em)

        embed = discord.Embed(title='You have been banned from The Coding Community', description=f'Banned by {member}')
        embed.add_field(name='Reason:', value=f'{reason}')
        await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def unban(self, ctx, *, member):
        banned_users = await ctx.guild.bans()
        member_name, member_discriminator = member.split("#")

        for ban_entry in banned_users:
            user = ban_entry.user

            if (user.name, user.discriminator) == (member_name, member_discriminator):
                await ctx.guild.unban(user)
                em = discord.Embed(title = f'You Unbanned {user.mention}')
                await ctx.send(embed = em)
                return

    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member:discord.Member = None,*,reason = 'No reason provided'):
        if not member:
            em = discord.Embed(title = 'Please specify a member.')
            await ctx.send(embed = em)
            return
        await member.kick()
        em = discord.Embed(title = f'You kicked {member}')
        await ctx.send(embed = em)
        embed = discord.Embed(title='You have been kicked from The Coding Community', description=f'Kicked by {member}')
        embed.add_field(name='Reason:', value=f'{reason}')
        await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(kick_members = True)
    async def mute(self,ctx, member:discord.Member = None,time:str = None,*,reason = 'No reason provided'):
        try:
            while True:
                try:
                    if member == None:
                        em = discord.Embed(title = 'Please specify a member.')
                        await ctx.send(embed = em)
                        return
                    if member == ctx.message.author:
                        embed = discord.Embed(title = 'No you may not mute yourself.')
                        await ctx.send(embed = embed)
                        break
                    else:
                        indicator = time[-1]
                        if indicator == "m" or indicator == "s" or indicator == 'h' or indicator == 'd':
                            pass
                        else:
                            await ctx.send('Incorrect Time Format.')
                            break
                        muted_give = discord.utils.get(ctx.guild.roles, name = 'Muted')
                        await member.add_roles(muted_give)
                        embed = discord.Embed(title = str(member) + ' was successfully muted by: ' + str(ctx.author) + ' for ' + str(time) + ' Reason:' + str(reason))
                        await ctx.send(embed = embed)
                        time = time[:-1]
                        if indicator == 'm':
                            await asyncio.sleep(int(time) * 60)
                        elif indicator == 'h':
                            await asyncio.sleep(int(time) * 3600)
                        elif indicator == 's':
                            await asyncio.sleep(int(time))
                        elif indicator == 'd':
                            await asyncio.sleep(int(time) * 86400)
                        else:
                            pass
                        await member.remove_roles(muted_give)
                        break
                except AttributeError:
                    muted = await ctx.guild.create_role(name = "Muted")
                    await ctx.message.channel.set_permissions(ctx.guild.get_role(muted.id), send_messages = False)
        except Exception:
            traceback.print_exc()

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def warn(self,ctx , member : discord.Member ,* , reason = "No reason Provided"):
        with open('warnings.json','r') as f:
            warns = json.load(f)
        if str(ctx.guild.id) not in warns:
            warns[str(ctx.guild.id)] = {}
        if str(member.id) not in warns[str(ctx.guild.id)]:
            warns[str(ctx.guild.id)][str(member.id)] = {}
            warns[str(ctx.guild.id)][str(member.id)]["warns"] = 1
            warns[str(ctx.guild.id)][str(member.id)]["warnings"] = [reason]
        else:
            warns[str(ctx.guild.id)][str(member.id)]["warnings"].append(reason)
        with open('warnings.json','w') as f:
            json.dump(warns , f)
            await ctx.send(f"{member.mention} was warned for: {reason}")

            embed = discord.Embed(title='You have been warned in The Coding Community', description=f'You received a warning from {member}')
            embed.add_field(name='Reason:', value=f'{reason}')
            await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def removewarn(self,ctx, member: discord.Member, num: int, *, reason='No reason provided.'):
        with open('warnings.json' , 'r') as f:
            warns = json.load(f)

        num -= 1
        warns[str(ctx.guild.id)][str(member.id)]["warns"] -= 1
        warns[str(ctx.guild.id)][str(member.id)]["warnings"].pop(num)
        with open('warnings.json' , 'w') as f:
            json.dump(warns , f)
            await ctx.send('Warn has been removed!')
            embed = discord.Embed(title='Your warn in The Coding Community has been removed', description=f'Your warning was removed by {ctx.author}')
            await member.send(embed=embed)

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def warns(self,ctx , member : discord.Member):
        with open('warnings.json', 'r') as f:
            warns = json.load(f)

        num = 1
        warnings = discord.Embed(title = f"{member}\'s warns")
        for warn in warns[str(ctx.guild.id)][str(member.id)]["warnings"]:
            warnings.add_field(name = f"Warn {num}" , value = warn)
            num += 1
        await ctx.send(embed = warnings)

    @commands.group()
    @commands.guild_only()
    @commands.max_concurrency(1, per=commands.BucketType.guild)
    @commands.has_permissions(manage_messages=True)
    async def prune(self, ctx):
        """ Removes messages from the current server. """
        if ctx.invoked_subcommand is None:
            await ctx.send_help(str(ctx.command))

    async def do_removal(self, ctx, limit, predicate, *, before=None, after=None, message=True):
        if limit > 2000:
            return await ctx.send(f'Too many messages to search given ({limit}/2000)')

        if before is None:
            before = ctx.message
        else:
            before = discord.Object(id=before)

        if after is not None:
            after = discord.Object(id=after)

        try:
            deleted = await ctx.channel.purge(limit=limit, before=before, after=after, check=predicate)
        except discord.Forbidden:
            return await ctx.send('I do not have permissions to delete messages.')
        except discord.HTTPException as e:
            return await ctx.send(f'Error: {e} (try a smaller search?)')

        deleted = len(deleted)
        if message is True:
            await ctx.send(f'🚮 Successfully removed {deleted} message{"" if deleted == 1 else "s"}.')

    @prune.command()
    async def embeds(self, ctx, search=100):
        """Removes messages that have embeds in them."""
        await self.do_removal(ctx, search, lambda e: len(e.embeds))

    @prune.command()
    async def files(self, ctx, search=100):
        """Removes messages that have attachments in them."""
        await self.do_removal(ctx, search, lambda e: len(e.attachments))

    @prune.command()
    async def mentions(self, ctx, search=100):
        """Removes messages that have mentions in them."""
        await self.do_removal(ctx, search, lambda e: len(e.mentions) or len(e.role_mentions))

    @prune.command()
    async def images(self, ctx, search=100):
        """Removes messages that have embeds or attachments."""
        await self.do_removal(ctx, search, lambda e: len(e.embeds) or len(e.attachments))

    @prune.command(name='all')
    async def _remove_all(self, ctx, search=100):

        await self.do_removal(ctx, search, lambda e: True)

    @prune.command()
    async def user(self, ctx, member: discord.Member, search=100):

        await self.do_removal(ctx, search, lambda e: e.author == member)

    @prune.command()
    async def contains(self, ctx, *, substr: str):

        if len(substr) < 3:
            await ctx.send('The substring length must be at least 3 characters.')
        else:
            await self.do_removal(ctx, 100, lambda e: substr in e.content)

    @prune.command(name='bots')
    async def _bots(self, ctx, search=100, prefix=None):
        """Removes a bot user's messages and messages with their optional prefix."""

        getprefix = prefix if prefix else self.config.prefix

        def predicate(m):
            return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(getprefix))

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='users')
    async def _users(self, ctx, prefix=None, search=100):
        """Removes only user messages. """

        def predicate(m):
            return m.author.bot is False

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='emojis')
    async def _emojis(self, ctx, search=100):
        """Removes all messages containing custom emoji."""
        custom_emoji = re.compile(r'<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]')

        def predicate(m):
            return custom_emoji.search(m.content)

        await self.do_removal(ctx, search, predicate)

    @prune.command(name='reactions')
    async def _reactions(self, ctx, search=100):
        """Removes all reactions from messages that have them."""

        if search > 2000:
            return await ctx.send(f'Too many messages to search for ({search}/2000)')

        total_reactions = 0
        async for message in ctx.history(limit=search, before=ctx.message):
            if len(message.reactions):
                total_reactions += sum(r.count for r in message.reactions)
                await message.clear_reactions()

        await ctx.send(f'Successfully removed {total_reactions} reactions.')

def setup(bot):
    bot.add_cog(Mod(bot))


import json
import argparse
import requests
import time

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

from tqdm import tqdm

def get_statistics(df):
    stats = {}
    for column in df.columns[-4:]:
        sequences_with_domain = df.groupby(column)['SP_PRIMARY'] \
            .unique().apply(lambda x: len(x)).sort_values(ascending=False)
        stats[column] = sequences_with_domain
    return stats

if __name__ == '__main__':

    # 1. Define arguments
    parser = argparse.ArgumentParser()
    ### Path of the files
    parser.add_argument('--pdb_to_uniprot_path',  type=str,   default='data/pdb/pdb_chain_uniprot.tsv')
    parser.add_argument('--pdb_to_cath_path',     type=str,   default='data/pdb/pdb_chain_cath_uniprot.tsv')
    parser.add_argument('--original_path',        type=str,   default='data/results/jackhmmer.tsv')

    # 2. Define dictionary of args
    args = parser.parse_args()

    # 3. Load files
    original = pd.read_csv(args.original_path, sep='\t', dtype=str)
    pdb_cath = pd.read_csv(args.pdb_to_cath_path, sep ='\t', header=1, dtype=str)
    pdb_uniprot = pd.read_csv(args.pdb_to_uniprot_path, sep ='\t', header=1, dtype=str)

    # 4. Slice CATH
    pdb_cath = pdb_cath[pdb_cath.SP_PRIMARY.isin(original.entry_ac)]

    # 5. Download data of CATH

    url = 'http://www.cathdb.info/version/v4_1_0/api/rest/domain_summary'
    cath_superfamily = []
    cath_ids = pdb_cath.CATH_ID.tolist()
    batch_size = 50
    delay = 3

    print('Starting queries. Total queries: {}'.format(len(cath_ids)))
    for i in range(0, len(cath_ids), batch_size):
        # Define batch ids
        batch_ids = cath_ids[i:min(len(cath_ids), i + batch_size)]
        for cath_id in tqdm(batch_ids):
            res = requests.get('/'.join([url, cath_id]), headers={'Accept': 'application/json'})
            if res.status_code == 400:
                cath_superfamily.append(None)
                continue
            res_dict = res.json()
            cath_superfamily.append(res_dict['data']['superfamily_id'])
        time.sleep(delay)

    # 6. Create final dataset
    ### ADD RESULTS ON PDB_CATH
    pdb_cath['CATH'] = cath_superfamily
    db_uniprot = pdb_uniprot[pdb_uniprot.SP_PRIMARY.isin(original.entry_ac)]
    pdb_uniprot = pdb_uniprot.merge(pdb_cath[['PDB', 'CATH_ID', 'CATH']], how='left', on='PDB')

    ### Parse CATH values
    cath = pdb_uniprot.groupby(by = ['SP_PRIMARY', 'CATH']).size().reset_index(name='counts')
    cath = cath.sort_values(by='SP_PRIMARY')

    C, A, T, H = [], [], [], []
    for cath_value in cath.CATH:
        c, a, t, h = cath_value.split('.')
        C.append(c)
        A.append('.'.join([c,a]))
        T.append('.'.join([c,a,t]))
        H.append('.'.join([c,a,t,h]))
    cath['Class'] = C
    cath['Architecture'] = A
    cath['Topology'] = T
    cath['Homologous'] = H
    cath.head()

    stat_superfamily = get_statistics(cath)
    # 7. Show results
    fig, ax = plt.subplots(2, 2, figsize=(18, 14))

    C = stat_superfamily['Class']
    ax[0, 0].bar(sorted(C.keys()), height=C.values)
    ax[0, 0].set_xlabel('Class')
    ax[0, 0].set_ylabel('Frequencies')
    ax[0, 0].set_title('Class Distribution')
    ax[0, 0].set_xticklabels(['Mainly Alpha', 'Mainly Beta', 'Alpha Beta'], rotation=0)
    ax[0, 0].grid()
    # A
    A = stat_superfamily['Architecture']
    ax[0, 1].bar(sorted(A.keys()), height=A.values)
    ax[0, 1].set_xlabel('Architecture')
    ax[0, 1].set_ylabel('Frequencies')
    ax[0, 1].set_title('Architecture Distribution')
    ax[0, 1].grid()
    # T
    T = stat_superfamily['Topology']
    ax[1, 0].bar(sorted(T.keys()), height=T.values)
    ax[1, 0].set_xlabel('Topology')
    ax[1, 0].set_ylabel('Frequencies')
    ax[1, 0].set_title('Topology Distribution')
    ax[1, 0].set_xticklabels(sorted(T.keys()), rotation=90)
    ax[1, 0].grid()
    # H
    S = stat_superfamily['Homologous']
    ax[1, 1].bar(sorted(S.keys()), height=S.values)
    ax[1, 1].set_xlabel('Homologous')
    ax[1, 1].set_ylabel('Frequencies')
    ax[1, 1].set_title('Superfamily Distribution')
    ax[1, 1].set_xticklabels(sorted(S.keys()), rotation=90)
    ax[1, 1].grid()

    print(cath)
    plt.show()


# -*- coding:utf-8 -*-
"""
cron: 0 30 0 * * *
new Env('微信小程序-口味王');
"""

import time
import os
try:
    import requests
except Exception as e:
    print(e, "\n缺少requests 模块，请执行命令安装：python3 -m pip install requests")
    exit(3)
'''
版本 v1.0.1
====================== Cookie 配置===========================
'''
mycookies = [
]
try:
    mycookies = os.environ["KWW_COOKIE"].split("&")
except:
    print("【提示】请先获取微信小程序[口味王]cookie,环境变量添加 KWW_COOKIE ,如有不懂加群：212796668、681030097、743744614")
    exit(3)
'''
#2|“口味王”槟榔曾冠名过《这！就是灌篮3》吗？——正确
#3|“口味王”槟榔曾赞助过综艺《这！就是街舞4》吗？——正确
#4|“口味王”是槟榔行业领导品牌；——正确
#6|口味王已连续4年举办“我要上大学”公益活动？——正确
#7|游戏上分时，使用“口味王”槟榔可以秒回状态？——正确
#8|开车犯困的时候，使用“口味王”槟榔可以秒回状态？——正确
#9|熬夜加班的时候，使用“口味王”槟榔可以秒回状态？——正确
#10|槟榔品牌中，“口味王”槟榔销量全国领先吗？——正确
#11|“口味王”槟榔曾赞助过电视剧《鬼吹灯之云南虫谷》吗？——正确
#12|“口味王”槟榔曾赞助过电视剧《将夜2》吗？——正确
#13|“口味王”槟榔曾赞助过电视剧《鬼吹灯之龙岭迷窟》吗？——正确
#15|“口味王”槟榔曾赞助过电视剧《巡回检察组》吗？——正确
#16|“口味王”槟榔曾赞助《欢乐喜剧人5》吗？——正确
#17|2019年“口味王”冠名虎牙英雄联盟S9全球总决赛直播吗？——正确
#18|口味王已连续6年开展“温暖回家”公益活动——正确
#19|“口味王”槟榔曾赞助过电视剧《巡警之海外行动》吗？——正确
#20|“口味王”槟榔是_____的槟榔品牌。——全国销量领先 "全国销量领先","全国高端销量领先","湖南销量领先","湖南高端销量领先"
#21|以下哪个是“和成天下”槟榔的特点？——以上全是 "10包高端槟榔，7包和成天下","全国高端销量领先","海南嫩青果，味美更耐嚼","以上全是"
#22|“和成天下”槟榔是全国高端销量领先的槟榔品牌吗？——正确
#23|10包高端槟榔，有几包是“和成天下”？——7 4,5,6,7
#24|10包高端槟榔，有7包是“和成天下”对吗？——正确
#27|“和成天下”槟榔生产需要多少道工艺？——22道
#28|“和成天下”槟榔生产需要22道工艺？——正确
#30|为什么“和成天下”坚持使用海南槟榔果生产？——以上都是 "海南槟榔果汁多肉厚","海南槟榔果果形匀称","海南槟榔果更耐嚼","以上都是"
#31|高端槟榔市场占有率最高的品牌是“和成天下”吗？——正确
#32|“和成天下”品牌采用海南原果的比例是多少？——100% "50%","80%","70%","100%"
#33|“和成天下”是哪一类槟榔的引领者和典型代表？——高端槟榔
#34|“和成天下”是高端槟榔槟榔的引领者和典型代表？——正确
#35|“和成天下”是湖南人更爱吃的槟榔吗？——正确
#36|“和成天下”曾赞助过芒果TV《野生厨房》吗？——正确
#38|“和成天下”采用的是_____槟榔？——海南嫩青果 海南嫩青果,湖南嫩青果,河南嫩青果,云南嫩青果
#39|“和成天下”品牌广告语：“海南_______，味美更耐嚼”——嫩青果 好果子,万宁果,嫩青果,秋前果
#41|“和成天下”品牌广告语：“_____嫩青果，味美更耐嚼”——海南
#42|“和成天下”槟榔原果来自全球槟榔黄金产区——海南吗？——正确
#43|“和成天下”槟榔是_____的槟榔品牌。——全国高端销量领先 "全国销量领先","全国高端销量领先","湖南销量领先","湖南高端销量领先"
#44|海南的槟榔果有什么特点——以上都是 "汁多肉厚","果形匀称","耐嚼","以上都是"
#45|全球槟榔的黄金产区在哪里——中国海南 "印度尼西亚","中国台湾","菲律宾","中国海南"
#46|海南的三大支柱产业是什么？——槟榔、椰子、橡胶   椰子、橡胶、芒果,槟榔、椰子、橡胶,槟榔、椰子、芒果,槟榔、橡胶、芒果
#48|与东南亚槟榔相比，海南槟榔更适合加工成干果进行咀嚼吗？——正确
#50|中国“四大南药”之首是什么？——槟榔 "益智仁","槟榔","砂仁","巴戟天"
#51|白居易的千古名句：“戴花红石竹，帔晕紫_____”——槟榔 "枸杞","黄芪","人参","槟榔"
#52|《本草纲目》中描述槟榔有哪些功效？——以上都是 解油,驱虫,除胀,以上都是
#53|邓丽君的歌曲：“高高的树上结_____，谁先爬上谁先尝”——槟榔 槟榔,椰子,榴莲,菠萝蜜
#55|“可疗饥怀香自吐，能消瘴疠暖如熏。”这句诗描写的是哪种植物？——槟榔树 "椰子树","橡胶树","槟榔树","橄榄树"
#56|西汉汉武帝曾制定_____作为皇室贡品进献——以上都是 "荔枝","槟榔","珍珠","以上都是"
#57|槟榔起源于哪里？——马来西亚 "菲律宾","越南","印度尼西亚","马来西亚"
#59|海南万宁被称为什么——槟榔之乡 槟榔之乡,芒果之乡,椰子之乡,凤梨之乡
#60|为什么海南是全球槟榔的黄金产区——以上都是 温差小,日照长,空气湿度高,以上都是
#61|海南万宁的槟榔果是槟榔中的黄金圣果吗？——正确
#62|国内嚼食槟榔以果肉为主，越南等东南亚国家则以带核槟榔为主——正确
#63|与东南亚槟榔相比，海南槟榔纤维细腻更适合咀嚼吗？——正确
#65|李白的千古名句：“何时黄金盘，一斛荐_____”——槟榔 "槟榔","黄芪","人参","枸杞"
#66|“若笋竹生竿，种之精硬，引茎直上，不生枝叶。”描写的是哪种植物？——槟榔树 "椰子树","橡胶树","槟榔树","橄榄树"
#67|“高高的树上结槟榔，谁先爬上谁先尝”是哪首歌的歌词？——《采槟榔》 "《采槟榔》","《摘槟榔》","《尝槟榔》","《品槟榔》"
#68|“开花树杪翻青箨，结子苞中皱锦纹。”这句诗描写的是哪种植物？——槟榔树 "槟榔树","橡胶树","椰子树","橄榄树"
#70|考古发现最早的槟榔遗骸是哪年？——公元前10,000年 "公元前1,000年","公元前3,000年","公元前7,000年","公元前10,000年"
#71|“朗是宾门篓似妾，结成一对好鸳鸯。”这句诗描写的是哪种植物？——槟榔树 椰子树,橡胶树,橄榄树,槟榔树
#72|槟榔果一般在什么时间采摘？——8~10月 8~10月,11~1月,2~4月,5~7月
====================== 题库 ===========================
'''
ktList = {'1':'',#题目未知
             '2':'正确',
             '3':'正确',
             '4':'正确',
             '5':'',#
             '6':'正确',
             '7':'正确',
             '8':'正确',
             '9':'正确',
             '10':'正确',
             '11':'正确',
             '12':'正确',
             '13':'正确',
             '14':'',#
             '15':'正确',
             '16':'正确',
             '17':'正确',
             '18':'正确',
             '19':'正确',
             '20':'全国销量领先',
             '21':'以上全是',
             '22':'正确',
             '23':'7',
             '24':'正确',
             '25':'',#
             '26':'',#
             '27':'22道',
             '28':'正确',
             '29':'',#
             '30':'以上都是',
             '31':'正确',
             '32':'100%',
             '33':'高端槟榔',
             '34':'正确',
             '35':'正确',
             '36':'正确',
             '37':'',#
             '38':'海南嫩青果',
             '39':'嫩青果',
             '40':'',#
             '41':'海南',
             '42':'正确',
             '43':'全国高端销量领先',
             '44':'以上都是',
             '45':'中国海南',
             '46':'槟榔、椰子、橡胶',
             '47':'',#
             '48':'正确',
             '49':'',#
             '50':'槟榔',
             '51':'槟榔',
             '52':'以上都是',
             '53':'槟榔',
             '54':'',#
             '55':'槟榔树',
             '56':'以上都是',
             '57':'马来西亚',
             '58':'',#
             '59':'槟榔之乡',
             '60':'以上都是',
             '61':'正确',
             '62':'正确',
             '63':'正确',
             '64':'',#
             '65':'槟榔',
             '66':'槟榔树',
             '67':'《采槟榔》',
             '68':'槟榔树',
             '69':'',#
             '70':'公元前10,000年',
             '71':'槟榔树',
             '72':'8~10月'
             }

'''
====================== 请求 ===========================
'''
def getApiBody(url, body):
    headers = {
        'Content-Type': 'application/json',
    }
    return requests.get(url=url,body=body, headers=headers, timeout=300).json()

def getApi(url, headers):
    return requests.get(url=url, headers=headers, timeout=300).json()

def getApiR(url, headers):
    return requests.get(url=url, headers=headers, allow_redirects=False, timeout=300)

if __name__ == '__main__':
    for i in range(len(mycookies)):
        print("用户【" + mycookies[i] + "】")
        url = 'https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=select-member-score&formName=searchForm&memberId=' + mycookies[i]
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
        res = getApi(url, headers)
        print("积分剩余 : " + str(res['rows'][0]))
        if int(res['rows'][0]) >= 888:
            print("积分大于 888 分，请去微信公众号【口味王】兑换红包")
        print("【每日签到】")
        res = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=selectSignInfo&formName=searchForm&memberId=' + mycookies[i], headers)
        propList = res['rows']['data']
        for prop in range(len(propList)):
            if propList[prop]['flag'] == "1":
                print(propList[prop]['formulaDesc'] + " " + ("未签到" if propList[prop]['flag'] == "0" else  "已签到") + "  签到奖励 " + propList[prop]['paramNo'])
                if propList[prop]['flag'] == "0":
                    body = {
                    "pageName": "AddSignSvmInfo",
                                "formName": "addForm",
                    'orderNo': propList[prop]['orderNo'],
                    'paramNo': propList[prop]['paramNo'],
                    'cateId': propList[prop]['cateId'],
                    'memberId': mycookies[i] ,
                    'memberName': "JDWXX" ,
                    }
                    jf = getApiBody('https://member.kwwblcj.com/member/api/submit/?userKeys=v1.0', body)
                    print(jf['msg'])
                    break
        print("【任务】")
        res = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=select-task-list&formName=searchForm&memberId=' + mycookies[i],headers)
        propList = res['rows']
        for prop in range(len(propList)):
            print(propList[prop]['taskTitle'] + "  " + "奖励积分:" +propList[prop]['rewardScore'] + " ->  " + ("待完成" if propList[prop]['complete'] == '0' else "已完成"))
            if propList[prop]['taskTitle'] == "开启签到提醒" and propList[prop]['complete'] == "0":
                print("【开启签到提醒】")
                jf = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=setOpenSignTaskFlag&formName=addForm&memberId=' + mycookies[i] + '&userCname=JDWXX&openId=o_V6_5Yo3mET81MVAQw4yYebL3zE', headers)
                print('完成' if jf['rows'][0] == 'T' else '失败，去手动完成任务')
                jf = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=setOpenSignTaskFlag&formName=addForm&memberId=' + mycookies[i] + '&userCname=JDWXX&openId=0', headers)
                print('完成' if jf['rows'][0] == 'T' else'失败，去手动完成任务')
            if propList[prop]['taskTitle'] == "订阅活动通知" and propList[prop]['complete'] == "0":
                print("【订阅活动通知】")
                jf = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=setOpenSubscribeTaskFlag&formName=addForm&memberId=' + mycookies[i] + '&userCname=JDWXX&openId=o_V6_5Yo3mET81MVAQw4yYebL3zE', headers)
                print('完成' if jf['rows'][0] == 'T' else '失败，去手动完成任务')
                jf = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=setOpenSubscribeTaskFlag&formName=addForm&memberId=' + mycookies[i] +'&userCname=JDWXX&openId=0', headers)
                print('完成' if jf['rows'][0] == 'T' else '失败，去手动完成任务')
        print("【每日阅读】")
        jf = getApi('https://member.kwwblcj.com/member/api/list/?userKeys=v1.0&pageName=setNewsReadTaskFlag&formName=addForm&memberId=' + mycookies[i] + '&userCname=JDWXX&articleTitle=undefined', headers)
        print("阅读日期：" + jf['rows'][0])
        print("【答题任务】")
        url = 'https://member.kwwblcj.com/member/api/info/?userKeys=v1.0&pageName=loginFreePlugin&formName=searchForm&uid=' + mycookies[i] +'&levelCode=K1&redirect=https%3A%2F%2F89420.activity-20.m.duiba.com.cn%2Fprojectx%2Fp129446ea%2Findex.html%3FappID%3D89420'
        res = getApi(url, headers)
        cookie = getApiR(res['result'], headers).headers.get('Set-Cookie')
        cookieList = cookie.split(";")
        cookie_wdata4 = ''
        cookie_w_ts = ''
        cookie__ac = ''
        for ii in range(len(cookieList)):
            if cookieList[ii].find('wdata4') != -1:
                cookie_wdata4 = cookieList[ii]
            if cookieList[ii].find('w_ts') != -1:
                cookie_w_ts = cookieList[ii]
            if cookieList[ii].find('_ac') != -1:
                cookie__ac = cookieList[ii]
        Cookie = cookie_wdata4 + ";" + cookie_w_ts + ";" + cookie__ac
        Cookie = Cookie.replace("HttpOnly,","")
        headers = {
            'Cookie': Cookie,
        }
        res = getApi('https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/start.do?user_type=0&is_from_share=1&_t=' + str(time.time()), headers)
        startId = str(res['data'])
        if startId == 'None':
            print("今日已答题")
            continue
        i = 1
        while i < 5:
            i += 1
            url = 'https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/getQuestion.do?startId=' + startId + '&user_type=0&is_from_share=1&_t=' + str(time.time())
            res = getApi(url, headers)
            print("题目ID：" + res['data']['id'] + " > " + res['data']['content'])
            answerList = res['data']['answerList']
            print(str(answerList))
            dt = False
            for jj in range(len(answerList)):
                if answerList[jj].find(ktList.get(res['data']['id'])) != -1:
                    print('找到答案 >' + ktList.get(res['data']['id']))
                    print('提交答案 > 提交值 >' + str(jj + 1))
                    url = 'https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/submit.do?answer=' + str(jj + 1) + '&startId=' + startId + '&user_type=0&is_from_share=1&_t=' + str(time.time())
                    res = getApi(url, headers)
                    print(res)
                    dt = True
                    break
            if dt == False:
                for jj in range(len(answerList)):
                    print(answerList[jj])
                    print(ktList.get(res['data']['id']))
                    if answerList[jj].find("正确") != -1 \
                            or answerList[jj].find("槟榔") != -1 \
                            or answerList[jj].find("海南") != -1 \
                            or answerList[jj].find("100%") != -1 \
                            or answerList[jj].find("中国") != -1 \
                            or answerList[jj].find("全国") != -1 \
                            or answerList[jj].find("领先") != -1:
                        print('未找到答案 找到默认配置规则')
                        print('提交答案 > 提交值 >' + str(jj + 1))
                        url = 'https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/submit.do?answer=' + str(jj + 1) + '&startId=' + startId + '&user_type=0&is_from_share=1&_t=' + str(time.time())
                        res = getApi(url, headers)
                        print(res)
                        dt = True
                        break
            if dt == False:
                print('未找到配置')
                print('提交答案 > 提交默认值 1')
                url = 'https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/submit.do?answer=1&startId=' + startId + '&user_type=0&is_from_share=1&_t=' + str(time.time())
                res = getApi(url, headers)
                print(res)
        # 领取奖励
        url = 'https://89420.activity-20.m.duiba.com.cn/projectx/p129446ea/answer/complete.do?startId=' + startId + '&user_type=0&is_from_share=1&_t=' + str(time.time())
        res = getApi(url, headers)
        print(res)


import os, sys, pickle
import numpy as np
from sklearn import metrics
from lehmer_mean import optimise_lehmer_mean, lehmer_mean
from local_accuracy import compute_local_accuracy, get_nearest_neighbours_densenet
sys.path.append('./models')
from model_utils import load_xy
import matplotlib.pyplot as plt

# NOTE: this code is super messy and needs refactoring

outputs = pickle.load(open('models/pkl/all-stacked-outputs.pkl', 'rb'))

X_densenet, _ = load_xy('densenet121')

test_size = 2000
num_cnns = 2
num_models = len(outputs['mobilenet'].keys())
true_labels = outputs['true_labels']['mobilenet']['test']

# returns ndarray (models, samples, classes) and list of model accuracies
def get_prediction_tensor ():
	tensor = np.zeros((num_models*num_cnns, test_size, 2))
	models = []
	modelnames = []
	for cnn in ['densenet121', 'mobilenet']:
		for modelname in outputs[cnn]:
			tensor[len(models)] = outputs[cnn][modelname]['test']
			models.append(outputs['acc'][cnn][modelname])
			modelnames.append(modelname)
			# models.append((cnn, modelname, outputs['acc'][cnn][modelname]))
	return tensor, np.array(models), modelnames

# tensor is tensor of predictions, models is list of model accuracies
# modelnames is a list of stacked model names, densenet first then mobilenet
tensor, models, modelnames = get_prediction_tensor()

# ensemble with a specific averaging function which is passed an ndarray (models, classes) and model accuracies and index for each sample and returns accuracy
def ensemble_predictions (tensor, models, fn):
	predictions = [fn(tensor[:,k,:], models, k) for k in range(tensor.shape[1])]
	predictions = np.argmax(predictions, axis=1)
	tn, fp, fn, tp = metrics.confusion_matrix(np.argmax(true_labels, axis=1), predictions).ravel()
	return {
		"accuracy": round(metrics.accuracy_score(np.argmax(true_labels, axis=1), predictions) * 100, 2),
		"sensitivity": round(tp/(tp+fn)*100, 2),
		"specificity": round(tn/(tn+fp)*100, 2)
	}

def en (title, fn):
	data = ensemble_predictions(tensor, models, fn)
	spaces = ' ' * (50 - len(title))
	print(f'{title}: {spaces} {data["accuracy"]}%      {data["sensitivity"]}%      {data["specificity"]}%')
print('Model' + ' ' * 47 + 'accuracy sensitivity specificity')

epsilon = 0.5

# returns optimised base p for Lehmer mean using a specific cnn and dataset
def get_p (cnn, dataset):
	return optimise_lehmer_mean(
		np.array([outputs[cnn][modelname][dataset] for modelname in sorted(outputs[cnn].keys())]).swapaxes(0,1) + epsilon,
		np.identity(2)[outputs['true_labels'][cnn][dataset]] + epsilon,
		w=np.clip(np.array([outputs['acc'][cnn][modelname] for modelname in sorted(outputs[cnn].keys())]) - 0.6, 0, 1)**3
	)

# takes a matrix (models, classes) and vec (models) and returns (classes,) using lehmer mean across columns
def lehmer_mat (mat, accuracies, index, weights=None):
	class_vecs = [c for c in mat.T]
	default_weights = np.clip(accuracies-0.6,0.01,1)**3
	weights = weights if weights is not None else default_weights #np.repeat(default_weights[np.newaxis, ...], test_size, axis=0)
	densenet_mat = np.transpose([lehmer_mean(c + epsilon, p_densenet, w=weights) for c in mat.T])
	mobilenet_mat = np.transpose([lehmer_mean(c + epsilon, p_mobilenet, w=weights) for c in mat.T])
	accs = [0.708, 0.675] # from results-eda.py
	weights = np.array(accs) / np.sum(accs)
	return densenet_mat * weights[0] + mobilenet_mat * weights[1]

# takes a matrix (models, classes) and vec (models) and returns (classes,) using lehmer mean across columns
def lehmer_mat_custom (mat, accuracies, p):
	class_vecs = [c for c in mat.T]
	weights = np.clip(accuracies-0.6,0.01,1)
	return np.transpose([lehmer_mean(c + epsilon, p, w=weights) for c in mat.T])

en('Best individual model', lambda mat, models, i: mat[np.argmax(models)])
en('Simple unweighted average', lambda mat, models, i: np.average(mat.T, axis=1).T)
en('Average weighted by accuracy', lambda mat, models, i: np.average(np.multiply(mat.T, np.clip(models-0.6,0,1)), axis=1).T)
for k in range(5):
	p = 0.6 + k/5
	en('L_p weighted by accuracy, p='+str(p), lambda mat, models, i: lehmer_mat_custom(mat, models, p))
for p in [-10, 0.01, 0.5, 10, -1000, 1000, -2.6, 4.8]:
	en('L_p weighted by accuracy, p='+str(p), lambda mat, models, i: lehmer_mat_custom(mat, models, p))

# takes ages to compute, and the output is the same every time, hence the float literals
p_densenet = 1.1756283000118866 #get_p('densenet121', 'valid')
# print(p_densenet)
p_mobilenet = 0.7142255422715837 #get_p('mobilenet', 'valid')
# print(p_mobilenet)

en('Optimised Lehmer mean weighted by accuracy', lehmer_mat)

def generate_local_accuracies ():
	all_la = []
	for k in range(tensor.shape[1]):
		mat = tensor[:,k,:]
		accuracies = models
		i = k

		x = X_densenet[i]
		indices, inverse_squares = get_nearest_neighbours_densenet(X_densenet[i], i)
		la = [] # local accuracies
		for i, modelname in enumerate(modelnames):
			cnn = ['densenet121', 'mobilenet'][int(i > len(modelnames)//2)]
			Y_hat = outputs[cnn][modelname]['all-train']
			la.append(compute_local_accuracy(Y_hat, X_densenet[i], indices, inverse_squares))
		weights = np.clip(np.array(la)-0.5,0.01,1)**3
		all_la.append(weights)
	return np.array(all_la)

la = generate_local_accuracies()

def local_acc_weighted_lehmer_mean (mat, accuracies, i):
	return lehmer_mat(mat, accuracies, None, weights=la[i])

def local_acc_weighted_mean (mat, accuracies, i):
	return np.average(np.multiply(mat.T, la[i]*1/4 + accuracies *3/4), axis=1).T

en('Optimised Lehmer mean weighted by local accuracy', local_acc_weighted_lehmer_mean)
en('Average weighted by local accuracy', local_acc_weighted_mean)

print('Best CNN (densenet121):                             70.8%')

def graph_lehmer_base ():
	ps_pos = np.logspace(-1.0, 2.0, num=50)
	ps = np.concatenate((-ps_pos[::-1], ps_pos))
	all_data = {
		"accuracy": [],
		"sensitivity": [],
		"specificity": []
	}
	for p in ps:
		data = ensemble_predictions(tensor, models, lambda mat, models, i: lehmer_mat_custom(mat, models, p))
		all_data['accuracy'].append(data['accuracy'])
		all_data['sensitivity'].append(data['sensitivity'])
		all_data['specificity'].append(data['specificity'])

	plt.xscale('symlog')
	plt.yscale('linear')
	plt.ylim(top=100, bottom=50)
	for key in all_data:
		plt.plot(ps, all_data[key], label=key[0].upper()+key[1:])
	plt.legend()
	plt.title('Performance Metrics versus Lehmer Mean Base')
	plt.ylabel('Percentage (linear scale)')
	plt.xlabel('Base (p) for Lehmer mean (log scale)')
	plt.show()


__author__ = 'xiaxuan'

from flask import Flask
from mongoengine import connect

app = Flask(__name__)
# app.config.from_object('config')
MONGODB_SETTINGS = {
                    'db': 'files',
                    "host": '103.235.225.39',
                    "port": 27021
                    }
app.config['MONGODB_DB'] = 'files'
app.config['MONGODB_HOST'] = 'localhost'
app.config['MONGODB_PORT'] = 27017

db = connect(db='files', host='103.235.225.39', port=27021)

from app import views
from app import models


import torch.nn as nn
import torch
from torch import autograd
import torch.nn.functional as F
from layer import U_Encoder2d, U_Decoder_lab2d, CrossTaskmodule2d
from layer import U_Encoder3d, U_Decoder_lab3d, CrossTaskmodule3d
from layer import DoubleConv2d, DoubleConv3d

n_filters = 16
nc = [int(n_filters*(2**i)) for i in range(5)]

class Generator3d(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(Generator3d, self).__init__()

        self.E_feature = U_Encoder3d(in_ch, nc)
        self.D_feature_lab = U_Decoder_lab3d(nc)
        self.D_feature_img = U_Decoder_lab3d(nc)
        self.conv10_seg = nn.Conv3d(nc[0], out_ch, 1)
        self.conv10_img = nn.Conv3d(nc[0], 1, 1)
        self.cross_task = CrossTaskmodule3d(nc)

    def forward(self, x, y, MIdex_t, MIdex_s):
        input_s = torch.cat([x, MIdex_s-MIdex_t], dim=1)
        F_target = self.E_feature(input_s)
        c9_Tseg = self.D_feature_lab(F_target)
        c9_Timg = self.D_feature_img(F_target)
        c9_Tseg_new = self.cross_task(c9_Tseg, c9_Timg)
        c10_Tseg = self.conv10_seg(c9_Tseg_new)
        out_Tseg = nn.Sigmoid()(c10_Tseg)
        out_Timg = self.conv10_img(c9_Timg)

        input_t = torch.cat([out_Timg, MIdex_t-MIdex_s], dim=1)
        F_source = self.E_feature(input_t)
        c9_Sseg = self.D_feature_lab(F_source)
        c9_Simg = self.D_feature_img(F_source)
        c9_Sseg_new = self.cross_task(c9_Sseg, c9_Simg)
        c10_Sseg = self.conv10_seg(c9_Sseg_new)
        out_Sseg = nn.Sigmoid()(c10_Sseg)
        out_Simg = self.conv10_img(c9_Simg)

        return out_Tseg, out_Timg, out_Sseg, out_Simg

class Discriminator3d(nn.Module):
    def __init__(self, n_modality):
        super(Discriminator3d, self).__init__()

        def discriminator_block(in_filters, out_filters, normalize=True):
            """Returns downsampling layers of each discriminator block"""
            layers = [nn.Conv3d(in_filters, out_filters, 4, stride=2, padding=1)]
            if normalize:
                layers.append(nn.InstanceNorm3d(out_filters))
            layers.append(nn.LeakyReLU(0.2, inplace=True))
            return layers

        self.D_src = nn.Sequential(
            *discriminator_block(1, nc[0], normalize=False),
            *discriminator_block(nc[0], nc[1]),
            *discriminator_block(nc[1], nc[2]),
            *discriminator_block(nc[2], nc[3]),
            #nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv3d(nc[3], 1, 4, padding=1)
        )

        self.D_cls = nn.Sequential(
            *discriminator_block(1, nc[0], normalize=False),
            *discriminator_block(nc[0], nc[1]),
            *discriminator_block(nc[1], nc[2]),
            *discriminator_block(nc[2], nc[3]),
            #nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv3d(nc[3], n_modality, 4, padding=1)
        )

    def forward(self, img):
        out_src = self.D_src(img)
        out_src = F.avg_pool3d(out_src, kernel_size=out_src.size()[2:5])
        out_src = nn.Sigmoid()(out_src)

        out_cls = self.D_cls(img)
        out_cls = F.avg_pool3d(out_cls, kernel_size=out_cls.size()[2:5])
        out_cls = nn.Softmax(dim=1)(out_cls)

        return out_src, out_cls

class Generator2d(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(Generator2d, self).__init__()
        self.E_feature = U_Encoder2d(in_ch, nc)
        self.D_feature_img = U_Decoder_lab2d(nc, out_ch)

    def forward(self, x, MIdex_t, MIdex_s):
        input_s = torch.cat([x, MIdex_s-MIdex_t], dim=1)
        F_target = self.E_feature(input_s)
        out_Timg = self.D_feature_img(F_target)

        input_t = torch.cat([out_Timg, MIdex_t-MIdex_s], dim=1)
        F_source = self.E_feature(input_t)
        out_Simg = self.D_feature_img(F_source)

        return out_Timg, out_Simg

class Discriminator2d(nn.Module):
    def __init__(self, n_modality):
        super(Discriminator2d, self).__init__()

        def discriminator_block(in_filters, out_filters, normalize=True):
            """Returns downsampling layers of each discriminator block"""
            layers = [nn.Conv2d(in_filters, out_filters, 4, stride=2, padding=1)]
            if normalize:
                layers.append(nn.InstanceNorm2d(out_filters))
            layers.append(nn.LeakyReLU(0.2, inplace=True))
            return layers

        self.D_src = nn.Sequential(
            *discriminator_block(1, nc[0], normalize=False),
            *discriminator_block(nc[0], nc[1]),
            *discriminator_block(nc[1], nc[2]),
            *discriminator_block(nc[2], nc[3]),
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(nc[3], 1, 4, padding=1)
        )

        self.D_cls = nn.Sequential(
            *discriminator_block(1, nc[0], normalize=False),
            *discriminator_block(nc[0], nc[1]),
            *discriminator_block(nc[1], nc[2]),
            *discriminator_block(nc[2], nc[3]),
            nn.ZeroPad2d((1, 0, 1, 0)),
            nn.Conv2d(nc[3], n_modality, 4, padding=1)
        )

    def forward(self, img):
        out_src = self.D_src(img)
        out_src = F.avg_pool2d(out_src, kernel_size=out_src.size()[2:4])
        out_src = nn.Sigmoid()(out_src)

        out_cls = self.D_cls(img)
        out_cls = F.avg_pool2d(out_cls, kernel_size=out_cls.size()[2:4])
        out_cls = nn.Softmax(dim=1)(out_cls)

        return out_src, out_cls

class ResidualBlock(nn.Module):
    """Residual Block with instance normalization."""

    def __init__(self, dim_in, dim_out):
        super(ResidualBlock, self).__init__()
        self.main = nn.Sequential(
            nn.Conv2d(dim_in, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
            nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True),
            nn.ReLU(inplace=True),
            nn.Conv2d(dim_out, dim_out, kernel_size=3, stride=1, padding=1, bias=False),
            nn.InstanceNorm2d(dim_out, affine=True, track_running_stats=True))

    def forward(self, x):
        return x + self.main(x)

class Generator2d_new(nn.Module):
    """Generator network."""

    def __init__(self, in_ch, out_ch, conv_dim=64, repeat_num=2):
        super(Generator2d, self).__init__()

        layers = []
        layers.append(nn.Conv2d(in_ch, conv_dim, kernel_size=7, stride=1, padding=3, bias=False))
        layers.append(nn.InstanceNorm2d(conv_dim, affine=True, track_running_stats=True))
        layers.append(nn.ReLU(inplace=True))

        # Down-sampling layers.
        curr_dim = conv_dim
        for i in range(2):
            layers.append(nn.Conv2d(curr_dim, curr_dim*2, kernel_size=3, stride=2, padding=1, bias=False))
            layers.append(nn.InstanceNorm2d(curr_dim*2, affine=True, track_running_stats=True))
            layers.append(nn.ReLU(inplace=True))
            curr_dim = curr_dim * 2

        # Bottleneck layers.
        for i in range(repeat_num):
            layers.append(ResidualBlock(dim_in=curr_dim, dim_out=curr_dim))

        # Up-sampling layers.
        for i in range(2):
            layers.append(nn.ConvTranspose2d(curr_dim, curr_dim//2, kernel_size=3, stride=2, padding=1, output_padding=1, bias=False))
            layers.append(nn.InstanceNorm2d(curr_dim//2, affine=True, track_running_stats=True))
            layers.append(nn.ReLU(inplace=True))
            curr_dim = curr_dim // 2

        layers.append(nn.Conv2d(curr_dim, out_ch, kernel_size=7, stride=1, padding=3, bias=False))
        layers.append(nn.Sigmoid())

        self.main = nn.Sequential(*layers)

    def forward(self, x, MIdex_s, MIdex_t, **kwargs):
        # onehot is one-hot vector of domain label with shape (batch, class)
        # c = onehot
        # c = c.view(c.size(0), c.size(1), 1, 1)
        # c = c.repeat(1, 1, x.size(2), x.size(3))
        # x = torch.cat([x, c], dim=1)

        input_s = torch.cat([x, MIdex_s-MIdex_t], dim=1)
        out_Timg = self.main(input_s)

        input_t = torch.cat([out_Timg, MIdex_t-MIdex_s], dim=1)
        out_Simg = self.main(input_t)

        return out_Timg, out_Simg

class U_Net3d(nn.Module):
    def __init__(self, in_ch, out_ch):
        super(U_Net3d, self).__init__()

        self.conv1 = DoubleConv3d(in_ch, nc[0])
        self.pool1 = nn.MaxPool3d(2, stride=2)
        self.conv2 = DoubleConv3d(nc[0], nc[1])
        self.pool2 = nn.MaxPool3d(2, stride=2)
        self.conv3 = DoubleConv3d(nc[1], nc[2])
        self.pool3 = nn.MaxPool3d(2, stride=2)
        self.conv4 = DoubleConv3d(nc[2], nc[3])
        self.pool4 = nn.MaxPool3d(2, stride=2)
        self.conv5 = DoubleConv3d(nc[3], nc[4])

        self.up6 = nn.ConvTranspose3d(nc[4], nc[3], 2, stride=2)
        self.conv6 = DoubleConv3d(nc[4], nc[3])
        self.up7 = nn.ConvTranspose3d(nc[3], nc[2], 2, stride=2)
        self.conv7 = DoubleConv3d(nc[3], nc[2])
        self.up8 = nn.ConvTranspose3d(nc[2], nc[1], 2, stride=2)
        self.conv8 = DoubleConv3d(nc[2], nc[1])
        self.up9 = nn.ConvTranspose3d(nc[1], nc[0], 2, stride=2)
        self.conv9 = DoubleConv3d(nc[1], nc[0])
        self.conv10 = nn.Conv3d(nc[0], out_ch, 1)

    def forward(self,x):
        c1=self.conv1(x)
        p1=self.pool1(c1)
        c2=self.conv2(p1)
        p2=self.pool2(c2)
        c3=self.conv3(p2)
        p3=self.pool3(c3)
        c4=self.conv4(p3)
        p4=self.pool4(c4)
        c5=self.conv5(p4)

        up_6 = self.up6(c5)
        merge6 = torch.cat([up_6, c4], dim=1)
        c6=self.conv6(merge6)
        up_7=self.up7(c6)
        merge7 = torch.cat([up_7, c3], dim=1)
        c7=self.conv7(merge7)
        up_8=self.up8(c7)
        merge8 = torch.cat([up_8, c2], dim=1)
        c8=self.conv8(merge8)
        up_9=self.up9(c8)
        merge9=torch.cat([up_9, c1], dim=1)
        c9=self.conv9(merge9)
        c10=self.conv10(c9)
        out = nn.Sigmoid()(c10)
        #out = nn.Softmax(dim=1)(c10)

        return out

class U_Net2d(nn.Module):
    def __init__(self,in_ch,out_ch):
        super(U_Net2d, self).__init__()

        self.conv1 = DoubleConv2d(in_ch, nc[0])
        self.pool1 = nn.MaxPool2d(2)
        self.conv2 = DoubleConv2d(nc[0], nc[1])
        self.pool2 = nn.MaxPool2d(2)
        self.conv3 = DoubleConv2d(nc[1], nc[2])
        self.pool3 = nn.MaxPool2d(2)
        self.conv4 = DoubleConv2d(nc[2], nc[3])
        self.pool4 = nn.MaxPool2d(2)
        self.conv5 = DoubleConv2d(nc[3], nc[4])

        self.up6 = nn.ConvTranspose2d(nc[4], nc[3], 2, stride=2)
        self.conv6 = DoubleConv2d(nc[4], nc[3])
        self.up7 = nn.ConvTranspose2d(nc[3], nc[2], 2, stride=2)
        self.conv7 = DoubleConv2d(nc[3], nc[2])
        self.up8 = nn.ConvTranspose2d(nc[2], nc[1], 2, stride=2)
        self.conv8 = DoubleConv2d(nc[2], nc[1])
        self.up9 = nn.ConvTranspose2d(nc[1], nc[0], 2, stride=2)
        self.conv9 = DoubleConv2d(nc[1], nc[0])
        self.conv10 = nn.Conv2d(nc[0], out_ch, 1)

    def forward(self, x):
        #x = torch.cat([x1, x2, x3], dim=1)
        c1=self.conv1(x)
        p1=self.pool1(c1)
        c2=self.conv2(p1)
        p2=self.pool2(c2)
        c3=self.conv3(p2)
        p3=self.pool3(c3)
        c4=self.conv4(p3)
        p4=self.pool4(c4)
        c5=self.conv5(p4)

        up_6= self.up6(c5)
        merge6 = torch.cat([up_6, c4], dim=1)
        c6=self.conv6(merge6)
        up_7=self.up7(c6)
        merge7 = torch.cat([up_7, c3], dim=1)
        c7=self.conv7(merge7)
        up_8=self.up8(c7)
        merge8 = torch.cat([up_8, c2], dim=1)
        c8=self.conv8(merge8)
        up_9=self.up9(c8)
        merge9=torch.cat([up_9,c1],dim=1)
        c9=self.conv9(merge9)
        c10=self.conv10(c9)
        #out = nn.Softmax(dim=1)(c10)
        out = nn.Sigmoid()(c10)

        return out


import sys

def f_gold ( s ) :
    n = len ( s )
    auxArr = [ ]
    if s [ 0 ] == '1' :
        auxArr.append ( 1 )
    for i in range ( 1 , n ) :
        if s [ i ] == '1' :
            auxArr.append ( auxArr [ i - 1 ] + 1 )
        else :
            auxArr.append ( auxArr [ i - 1 ] )
    count = 0
    for i in range ( n - 1 , - 1 , - 1 ) :
        if s [ i ] == '1' :
            count += auxArr [ i ]
    return count

if __name__ == '__main__':
    param = [
    ('OGiOkJF',),
    ('517376',),
    ('11',),
    ('Ze',),
    ('8763644247018',),
    ('00111010001',),
    ('HGwkBKUOVu',),
    ('652',),
    ('101000011110',),
    ('kvdpG ',)
        ]
    n_success = 0
    print("class,mutant,test_index,result")
    for i, parameters_set in enumerate(param):
        try:
            print("NUMBER_OF_SUBSTRINGS_WITH_ODD_DECIMAL_VALUE_IN_A_BINARY_STRING," + sys.argv[1] + "," + str(i) + "," + str(f_gold(*parameters_set)))
        except:
            print("NUMBER_OF_SUBSTRINGS_WITH_ODD_DECIMAL_VALUE_IN_A_BINARY_STRING," + sys.argv[1] + "," + str(i) + ",EXCEPTION")