import pandas
import numpy
import matplotlib.pyplot as plt
df=pandas.read_csv('Preprocessed/data_combined.csv')
# print (df[:5])
df['THRESTBPS'] = df['THRESTBPS'].replace(['?'],'120')
df['THRESTBPS'] = df['THRESTBPS'].astype('int64')
v=df.FBS.values=='?'
#randomly filling values with 80% with 0 and 20% with 1s
df.loc[v, 'FBS'] = numpy.random.choice(('0','1'), v.sum(), p=(0.8,0.2))
# print (df['FBS'].value_counts())
df['FBS']=df['FBS'].astype('int64')
df['CHOL'].value_counts().head()
df['CHOL']=df['CHOL'].replace('?','-69')#temporarily replacing ? with -69
df['CHOL']=df['CHOL'].astype('int64')
k=int(df[df['CHOL']!=-69]['CHOL'].mean())
df['CHOL']=df['CHOL'].replace(-69,k)
df['THALACH'].value_counts().head()
df['THALACH']=df['THALACH'].replace('?','-69')#temporarily replacing ? with -69
df['THALACH']=df['THALACH'].astype('int64')
k=int(df[df['THALACH']!=-69]['THALACH'].mean())
df['THALACH']=df['THALACH'].replace(-69,k)
v=df.EXANG.values=='?'
df.loc[v,'EXANG'] = numpy.random.choice(('0','1'), v.sum(), p=(0.61,0.39))
df['EXANG']=df["EXANG"].astype('int64')
df['OLDPEAK']=df['OLDPEAK'].replace('?','-69')#temporarily replacing ? with -69
df['OLDPEAK']=df['OLDPEAK'].astype('float64')
k=df[df['OLDPEAK']!=-69]['OLDPEAK'].mean()
df['OLDPEAK']=df['OLDPEAK'].replace(-69,numpy.round(k,1))
v=df.SLOPE.values=='?'
df.loc[v,'SLOPE'] = numpy.random.choice(('2','1','3'), v.sum(), p=(0.6,0.30,0.10))
# print df['SLOPE'].value_counts()
df['SLOPE']=df['SLOPE'].astype('int64')
v=df.CA.values=='?'
df.loc[v,'CA'] = numpy.random.choice(('0','1','2','3'), v.sum(), p=(0.60,0.20,0.13,0.07))
df['CA']=df['CA'].astype('int64')
# print df['CA'].value_counts()
df['THAL']=df['THAL'].replace('?',-1)
'''
df['THAL']=df['THAL'].replace('?',-1)
for row in df.iterrows():
    if row['THAL']==-1 and row['CATEGORY']>=1:
        df.loc[row.Index, 'ifor'] = 7

    elif row['THAL']==-1 and row['CATEGORY']==0:
        df.loc[row.Index, 'ifor'] = 3
'''
df.loc[(df['THAL']==-1)&(df['CATEGORY']!=0),'THAL']='7'
#print df['THAL'].value_counts()
df.loc[(df['THAL']==-1)&(df['CATEGORY']==0),'THAL']='3'
# print df['THAL'].value_counts()
df['THAL']=df['THAL'].astype('int64')
dummies = pandas.get_dummies(df["CP"],prefix="CP")
df = df.join(dummies)

dummies = pandas.get_dummies(df["RESTECG"],prefix="RESTECG")
df      = df.join(dummies)

dummies = pandas.get_dummies(df["SLOPE"],prefix="SLOPE")
df      = df.join(dummies)

dummies = pandas.get_dummies(df["THAL"],prefix="THAL")
df      = df.join(dummies)

#dummies = pandas.get_dummies(df["EXANG"],prefix="EXANG")
#df = df.join(dummies)

#del df['SEX']
del df['CP']
del df['RESTECG']
del df['SLOPE']
del df['THAL']
#del df['EXANG']
print (df.dtypes)

for g in df.columns:
    if df[g].dtype=='uint8':
        df[g]=df[g].astype('int64')

df.dtypes
df.loc[df['CATEGORY']>0,'CATEGORY']=1
stdcols = ["AGE","THRESTBPS","CHOL","THALACH","OLDPEAK"]
nrmcols = ["CA"]
stddf   = df.copy()
stddf[stdcols] = stddf[stdcols].apply(lambda x: (x-x.mean())/x.std())
stddf[nrmcols] = stddf[nrmcols].apply(lambda x: (x-x.min())/(x.max()-x.min()))
#stddf[stdcols] = stddf[stdcols].apply(lambda x: (x-x.mean())/(x.max()-x.min()))

for g in stdcols:
    print (g,max(stddf[g]),min(stddf[g]))

for g in nrmcols:
    print (g,max(stddf[g]),min(stddf[g]))

df_copy=stddf.copy()
df_copy=df_copy.drop(['CATEGORY'],axis=1)

dat=df_copy.values
labels=df['CATEGORY'].values

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(dat,labels, test_size=0.25, random_state=42)

from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import ExtraTreesClassifier
import xgboost as xgb
from sklearn.model_selection import GridSearchCV,cross_val_score
from sklearn import  metrics

clf = ExtraTreesClassifier()
clf = clf.fit(dat,labels)
g=clf.feature_importances_
c=stddf.drop(['CATEGORY'],axis=1).columns
model = SelectFromModel(clf, prefit=True)
X_new = model.transform(dat)

tx_train,tx_test,ty_train,ty_test=train_test_split(X_new,labels, test_size=0.25, random_state=42)

eval_set = [(x_test, y_test)]
model = XGBClassifier()
model.fit(x_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True)
y_pred = model.predict(x_test)
predictions = [round(value) for value in y_pred]
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))

from xgboost import plot_importance
from matplotlib import pyplot
plot_importance(model)
pyplot.show()
# from xgboost import plot_tree
# plot_tree(model)
# pyplot.show()
data = xgb.DMatrix(x_train,label=(y_train>0))
params = {
            'booster':'gbtree',
            'objective':'multi:softmax',
            'num_class':2,
            'eta':0.5,
            'max_depth':70,
            'subsample':1.0,
            'min_child_weight':5,
            'colsample_bytree':0.75,
            'scale_pos_weight':0.9,
            'eval_metric':'merror',
            'gamma':0.3,
            'lambda':200
}
num_round = 100
ret = xgb.cv(params,data,num_boost_round=num_round,nfold=10)

print('test-auc: ',1-ret.iloc[num_round-1][0])


import os
from spack import *

class Libcircle(Package):
    """libcircle provides an efficient distributed queue on a cluster,
       using self-stabilizing work stealing."""

    homepage = "https://github.com/hpc/libcircle"

    version('0.2.1-rc.1', '2b1369a5736457239f908abf88143ec2',
             url='https://github.com/hpc/libcircle/releases/download/0.2.1-rc.1/libcircle-0.2.1-rc.1.tar.gz')

    depends_on('mpi')

    def install(self, spec, prefix):
        configure("--prefix=" + prefix)
        make()
        make("install")


import pytube

url = 'https://www.youtube.com/watch?v=P5t0-X_OM5Y&t=0s'

video = pytube.YouTube(url)
'''
for stream in video.streams:
    if "video" in str(stream) and "mp4" in str(stream):
        print (stream)
'''

stream = video.streams.first()
print("Downloading...")
stream.download(output_path= r"Censored\Youtube Downloader\Downloaded")
print("Done")


from selenium.webdriver.remote.webdriver import WebDriver

# a configured instance of WebDriver
_DRIVER_INSTANCE = None

# a base url that all page object's will use when the navigate() mathod is
# called.
_BASE_URL = None

# the number of seconds to wait while looking up an element before timeout
_ELEMENT_LOOKUP_TIMEOUT = 10

def set_driver(driver):
    """
    Set the instance of web driver to be used throughout the library.
    :param driver:
    :return:
    """
    if not isinstance(driver, WebDriver):
        raise RuntimeError('{} must be an instance of WebDriver'.format(driver))

    global _DRIVER_INSTANCE
    _DRIVER_INSTANCE = driver

def get_driver():
    global _DRIVER_INSTANCE
    if not isinstance(_DRIVER_INSTANCE, WebDriver):
        raise RuntimeError('An instance of WebDriver has not been configured, '
                           'please call set_instance() with a valid instance '
                           'of WebDriver')

    return _DRIVER_INSTANCE

def set_base_url(url: str):
    global _BASE_URL
    _BASE_URL = url

def get_base_url():
    global _BASE_URL
    return _BASE_URL


import tempfile
from contextlib import suppress
from getpass import getpass
from typing import Callable, Dict, Iterator, Optional, Tuple, Union

# 3rd party
import click
from consolekit.input import confirm
from consolekit.terminal_colours import ColourTrilean, Fore, resolve_color_default
from deprecation_alias import deprecated
from domdf_python_tools.paths import PathPlus
from domdf_python_tools.typing import PathLike
from dulwich.errors import NotGitRepository
from dulwich.porcelain import fetch
from github3 import GitHub, orgs, repos, users
from github3.exceptions import NotFoundError
from github3.repos import contents
from github3.repos.branch import Branch
from github3_utils import echo_rate_limit as _utils_echo_rate_limit
from github3_utils import get_user as _utils_get_user
from github3_utils import protect_branch, secrets
from github3_utils.check_labels import check_status_labels
from packaging.version import InvalidVersion, Version
from repo_helper.core import RepoHelper
from repo_helper.files.ci_cd import ActionsManager, platform_ci_names
from repo_helper.utils import set_gh_actions_versions
from southwark.repo import Repo

# this package
from repo_helper_github._github import Github
from repo_helper_github._types import _EditKwargs
from repo_helper_github.cli import github_command
from repo_helper_github.exceptions import (
		BadUsername,
		ErrorCreatingRepository,
		NoSuchBranch,
		NoSuchRepository,
		OrganizationError
		)
from repo_helper_github.secret_validation import no_op_validator, validate_pypi_token

__author__: str = "Dominic Davis-Foster"
__copyright__: str = "2020-2021 Dominic Davis-Foster"
__license__: str = "MIT License"
__version__: str = "0.8.1"
__email__: str = "dominic@davis-foster.co.uk"

__all__ = [
		"github_command",
		"echo_rate_limit",
		"GitHubManager",
		"IsolatedGitHubManager",
		"encrypt_secret",
		"compile_required_checks",
		]

echo_rate_limit = deprecated(
		deprecated_in="0.5.0",
		removed_in="1.0.0",
		current_version=__version__,
		details="Use the new 'github3-utils' package instead.",
		func=_utils_echo_rate_limit,
		)

get_user = deprecated(
		deprecated_in="0.6.0",
		removed_in="1.0.0",
		current_version=__version__,
		details="Use the new 'github3-utils' package instead.",
		func=_utils_get_user,
		)

def _lower(string: str) -> str:
	return string.lower().replace('_', '-')

class GitHubManager(RepoHelper):
	"""
	Subclass of :class:`repo_helper.core.RepoHelper`
	with additional functions to update the repository metadata on GitHub.

	:param token: The token to authenticate with the GitHub API.
	:param target_repo: The path to the root of the repository to manage files for.
	:param managed_message: Message placed at the top of files to indicate that they are managed by ``repo_helper``.
	:param verbose: Whether to show information on the GitHub API rate limit.
	:param colour: Whether to use coloured output.

	.. versionchanged:: 0.3.0  Added the ``verbose`` and ``colour`` options.

	.. latex:clearpage::
	.. autosummary-widths:: 47/100
	"""  # noqa: D400

	#:
	github: GitHub

	verbose: bool
	"""
	Whether to show information on the GitHub API rate limit.

	.. versionadded: 0.3.0
	"""

	colour: ColourTrilean
	"""
	Whether to use coloured output.

	.. versionadded: 0.3.0
	"""

	def __init__(
			self,
			token: str,
			target_repo: PathLike,
			managed_message: str = "This file is managed by 'repo_helper'. Don't edit it directly.",
			*,
			verbose: bool = False,
			colour: ColourTrilean = True,
			):
		super().__init__(target_repo, managed_message)

		self.github = Github(token=token)
		self.verbose = verbose
		self.colour = resolve_color_default(colour)
		self.load_settings()

	def echo_rate_limit(self):
		"""
		Contextmanager to echo the GitHub API rate limit before and after making a series of requests.
		"""

		return _utils_echo_rate_limit(self.github, self.verbose)

	def new(self, org: bool = False) -> int:
		"""
		Create a new GitHub repository for this project.

		:param org: Whether the repository should be created for the organization set as ``username``,
			or for the authenticated user (default).

		:rtype:

		.. versionchanged:: 0.3.0

			* Removed the ``verbose`` option. Provide it to the class constructor instead.
			* Added the ``org`` argument.
		"""

		with self.echo_rate_limit():
			user = self.get_org_or_user(org)
			repo_name = self.templates.globals["repo_name"]

			repo: Optional[repos.Repository]

			if org:
				repo = user.create_repository(repo_name, **self.get_repo_kwargs())
			else:
				repo = self.github.create_repository(repo_name, **self.get_repo_kwargs())

			if repo is None:
				raise ErrorCreatingRepository(user.login, repo_name, org=org)

			self.update_topics(repo)
			click.echo(f"Success! View the repository online at {repo.html_url}")

			try:
				dulwich_repo = Repo(self.target_repo)
			except NotGitRepository:
				return 0

			config = dulwich_repo.get_config()
			config.set(("remote", "origin"), "url", repo.ssh_url.encode("UTF-8"))
			config.set(("remote", "origin"), "fetch", b"+refs/heads/*:refs/remotes/origin/*")
			config.write_to_path()

			fetch(dulwich_repo, remote_location="origin")

		return 0

	def update(self, org: bool = False) -> int:
		"""
		Update the GitHub repository for this project.

		:param org: Whether the repository should be created for the organization set as ``username``,
			or for the authenticated user (default).

		:rtype:

		.. versionchanged:: 0.3.0

			* Removed the ``verbose`` option. Provide it to the class constructor instead.
			* Added the ``org`` argument.
		"""

		with self.echo_rate_limit():
			user = self.get_org_or_user(org)
			repo_name = self.templates.globals["repo_name"]
			repo: repos.Repository = self._get_repository(user, repo_name, org)

			# TODO: add config option for allow_merge_commit

			repo.edit(
					name=repo.name,
					**self.get_repo_kwargs(),
					allow_merge_commit=False,
					)

			self.update_topics(repo)
			click.echo("Up to date!")

		return 0

	def _get_repository(
			self,
			user: Union[users.User, orgs.Organization],
			repository: str,
			org: bool,
			) -> repos.Repository:
		try:
			repo: Optional[repos.Repository] = self.github.repository(user.login, repository)
		except NotFoundError:
			repo = None

		if repo is None:
			raise NoSuchRepository(user.login, repository, org=org)

		return repo

	def get_org_or_user(self, org: bool = False) -> Union[orgs.Organization, users.User]:
		"""
		If ``org`` is :py:obj:`True`, returns the :class:`~github3.orgs.Organization` object representing the
		GitHub org that owns the repository.

		If ``org`` is :py:obj:`False`, returns the :class:`~github3.users.AuthenticatedUser` object representing the
		GitHub user that owns the repository.

		.. versionadded:: 0.3.0

		:param org:
		"""  # noqa: D400

		user = _utils_get_user(self.github)

		if org:
			self.assert_org_member(user)
			return self.github.organization(self.templates.globals["username"])
		else:
			self.assert_matching_usernames(user)
			return user

	def secrets(
			self,
			org: bool = False,
			overwrite: Optional[bool] = None,
			PYPI_TOKEN: Optional[str] = None,
			ANACONDA_TOKEN: Optional[str] = None
			) -> int:
		"""
		Set or update the secrets of the GitHub repository for this project.

		.. versionadded:: 0.3.0

		:param org: Whether the repository should be created for the organization set as ``username``,
			or for the authenticated user (default).
		:param overwrite: Overwrite existing values.
		:default overwrite: ask first.

		``PYPI_TOKEN`` and ``ANACONDA_TOKEN`` can either be passed as keyword arguments to this function
		or provided at the interactive prompt.

		:rtype:

		.. versionchanged:: 0.4.0  Added ``overwrite``, ``PYPI_TOKEN``, ``ANACONDA_TOKEN`` options.
		"""

		with self.echo_rate_limit():
			user = self.get_org_or_user(org)
			repo_name = self.templates.globals["repo_name"]
			repo: repos.Repository = self._get_repository(user, repo_name, org)

			# List of existing secrets.
			existing_secrets = secrets.get_secrets(repo)

			# Public key to encrypt secrets with.
			public_key = secrets.get_public_key(repo)

			ret = 0
			target_secrets: Dict[str, Callable[[str], Tuple[bool, str]]] = {"PYPI_TOKEN": validate_pypi_token}

			if self.templates.globals["enable_conda"]:
				target_secrets["ANACONDA_TOKEN"] = no_op_validator

			for secret_name in sorted(target_secrets):
				if overwrite is not None:
					update = True
				elif secret_name in existing_secrets:
					click.echo(f"A value for the secret {secret_name!r} already exists. ")
					update = confirm("Do you want to update the secret?")
				else:
					update = True

				if update:
					operation = "update" if secret_name in existing_secrets else "create"

					secret_value = locals().get(secret_name, None) or getpass(f"{secret_name}: ")

					valid, invalid_reason = target_secrets[secret_name](secret_value)
					if not valid:
						raise click.Abort(
								f"The value for {secret_name} does not appear to be valid: {invalid_reason}"
								)

					response = secrets.set_secret(
							repo,
							secret_name=secret_name,
							value=secret_value,
							public_key=public_key,
							)

					if response.status_code not in {200, 201, 204}:
						message = f"Could not {operation} the secret {secret_name!r}: Status {response.status_code}"
						click.echo(Fore.YELLOW(message), color=self.colour)
						ret |= 1
					else:
						message = f"Successfully {operation}d the secret {secret_name!r}."
						click.echo(Fore.GREEN(message), color=self.colour)

		return ret

	def protect_branch(self, branch: str, org: bool = False) -> int:
		"""
		Update branch protection for the given branch.

		This requires that the Linux and Windows tests pass, together with the mypy check.

		.. versionadded:: 0.4.0

		:param branch: The branch to update protection for.
		:param org: Whether the repository should be created for the organization set as ``username``,
			or for the authenticated user (default).

		:rtype:

		:raises:

			* :exc:`~.NoSuchBranch` if the branch is not found.
			* :exc:`~.NoSuchRepository` if the repository is not found.

		.. latex:clearpage::
		"""

		with self.echo_rate_limit():
			user = self.get_org_or_user(org)
			repo_name = self.templates.globals["repo_name"]
			repo: repos.Repository = self._get_repository(user, repo_name, org)

			gh_branch: Optional[Branch] = repo.branch(branch)
			if not gh_branch:
				raise NoSuchBranch(user.login, repo_name, branch)

			required_checks = list(compile_required_checks(self))

			protect_branch(gh_branch, status_checks=required_checks)

			# This seems to only work if its run twice
			protect_branch(gh_branch, status_checks=required_checks)

		click.echo("Up to date!")
		return 0

	def assert_matching_usernames(self, user: users.User):
		"""
		Assert that the username configured in ``repo_helper.yml`` matches that of the authenticated user.

		:param user:
		"""

		username = self.templates.globals["username"]

		if user.login != username:
			raise BadUsername(
					f"The username configured in 'repo_helper.yml' ({username}) "
					f"differs from that of the authenticated user ({user.login})!\n"
					f"If {self.templates.globals['username']!r} is an organization you should use the --org flag.",
					username=username,
					)

	def assert_org_member(self, user: users.User):
		"""
		Assert that the organization configured in ``repo_helper.yml`` exists, and the authenticated user is a member.

		:param user:
		"""

		username = self.templates.globals["username"]

		def error():
			raise OrganizationError(
					f"Either the organization configured in 'repo_helper.yml' ({username}) "
					f"does not exist or the authenticated user ({user.login}) is not a member!",
					username,
					)

		try:
			org = self.github.organization(username)
		except NotFoundError:
			raise error()

		if not org.is_member(user.login):
			raise error()

	def update_topics(self, repo: repos.Repository):
		"""
		Update the repository's topics.

		:param repo:
		"""
		# TODO: other languages detected in repo

		raw_topics = repo.topics()
		if raw_topics is None:
			topics = set()
		else:
			topics = set(raw_topics.names)

		topics.add("python")
		topics.update(self.templates.globals["keywords"])
		repo.replace_topics(sorted(map(_lower, topics)))

	def get_repo_kwargs(self) -> _EditKwargs:
		r"""
		Returns the keyword arguments used when creating and updating repositories.

		:rtype: :class:`~.typing.Dict`\[:class:`str`, :py:obj:`~.typing.Union`\[:class:`str`, :class:`bool`]]
		"""

		edit_kwargs: _EditKwargs = {"description": self.templates.globals["short_desc"]}

		if self.templates.globals["enable_docs"]:
			edit_kwargs["homepage"] = self.templates.globals["docs_url"]

		return edit_kwargs

	def create_labels(self, org: bool = False) -> int:
		"""
		Create labels for this repository.

		.. versionadded:: 0.5.0

		:param org: Whether the repository should be created for the organization set as ``username``,
			or for the authenticated user (default).
		"""

		with self.echo_rate_limit():
			user = self.get_org_or_user(org)
			repo_name = self.templates.globals["repo_name"]
			repo: repos.Repository = self._get_repository(user, repo_name, org)

			current_labels = {label.name: label for label in repo.labels()}

			for label in check_status_labels.values():
				if label.name in current_labels:
					current_labels[label.name].update(**label.to_dict())
				else:
					label.create(repo)
					click.echo(f"Created label {label.name}")

		click.echo("Up to date!")

		return 0

encrypt_secret = deprecated(
		deprecated_in="0.5.0",
		removed_in="1.0.0",
		current_version=__version__,
		details="Use the new 'github3-utils' package instead.",
		func=secrets.encrypt_secret,
		)

encrypt_secret.__doc__ = (encrypt_secret.__doc__ or '').replace(
		":func:`~.get_secrets`",
		":func:`~github3_utils.secrets.get_secrets`",
		)

def compile_required_checks(repo: RepoHelper) -> Iterator[str]:
	"""
	Returns an iterator over the names of required checks for the given repository.

	.. versionadded:: 0.4.0

	:param repo:
	"""

	actions_manager = ActionsManager(repo.target_repo, repo.templates)

	for platform in repo.templates.globals["platforms"]:
		if platform not in platform_ci_names:
			continue

		if platform == "Windows":
			ci_platform = platform_ci_names[platform]
			py_versions = actions_manager.get_windows_ci_versions()
		elif platform == "Linux":
			ci_platform = platform_ci_names[platform]
			py_versions = actions_manager.get_linux_ci_versions()
		# elif platform == "macOS":
		# 	ci_platform = platform_ci_names[platform]
		# 	py_versions = actions_manager.get_macos_ci_versions()
		else:
			continue

		for version in set_gh_actions_versions(py_versions):
			if version == "pypy-3.7":
				continue

			with suppress(InvalidVersion):
				if Version(version).is_prerelease:
					continue

			yield f"{ci_platform} / Python {version}"

	yield from [f"mypy / {platform_ci_names['Linux']}", "Flake8"]

	if repo.templates.globals["enable_docs"]:
		yield "docs"

GithubManager = GitHubManager

class IsolatedGitHubManager(GitHubManager):
	"""
	Subclass of :class:`~.GitHubManager` which can be used isolated from the repository
	and its ``repo_helper.yml`` config file.

	.. versionadded:: 0.4.0

	:param token: The token to authenticate with the GitHub API.
	:param username: The username of the GitHub account hosting the repository.
	:param repo_name: The name of GitHub repository.
	:param managed_message: Message placed at the top of files to indicate that they are managed by ``repo_helper``.
	:param verbose: Whether to show information on the GitHub API rate limit.
	:param colour: Whether to use coloured output.
	"""  # noqa: D400

	def __init__(
			self,
			token: str,
			username: str,
			repo_name: str,
			*,
			managed_message="This file is managed by 'repo_helper'. Don't edit it directly.",
			verbose: bool = False,
			colour: ColourTrilean = True,
			):

		self._tmpdir = tempfile.TemporaryDirectory()

		self.github = Github(token=token)
		self.verbose = verbose
		self.colour = resolve_color_default(colour)

		target_repo = PathPlus(self._tmpdir.name)
		config_file_name = "repo_helper.yml"

		github_repo: repos.Repository = self.github.repository(username, repo_name)
		contents_from_github: contents.Contents = github_repo.file_contents(config_file_name)
		(target_repo / config_file_name).write_bytes(contents_from_github.decoded)

		RepoHelper.__init__(self, target_repo, managed_message)

		self.load_settings()

	def __del__(self):
		self._tmpdir.cleanup()


# -*- coding: utf-8 -*-
import os
import unicodecsv
from items import SofangItem
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

class SofangPipeline(object):
    def process_item(self, item, spider):
        if isinstance(item,SofangItem):
            row_content=[item['name'],item['address'],item['area'],item['price'],item['m_price'],item['lon'],item['lat']]
            output_excel = "E:\\sofang.csv"
            field_names = [u"名字", u"地址", u"面积", u"平米价格", u"月租" ,"lon", "lat"]
            if os.path.isfile(output_excel) == False:
                with open(output_excel, 'w') as f:
                    w = unicodecsv.DictWriter(f, field_names,encoding='utf-8-sig')
                    w.writeheader()
                    # w.writerow(field_names)

            with open(output_excel, 'a') as f:
                w = unicodecsv.writer(f,encoding='utf-8-sig')
                w.writerow(row_content)
            return item


from flask import Flask,request, render_template

import subprocess
app = Flask(__name__)

@app.route("/", methods=["GET","POST"])
def get_cmd():
    if request.method == "GET":

        return render_template("email.html")

    if request.method == "POST":
        if request.form.get("email"):
            url = request.form.get("email")
            temp =  str(subprocess.check_output(["curl",url]))+ " has succesfully subscribed to AppSecEngineer"
        return render_template("email.html",data=temp)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=3000)


#!/usr/bin/env python3

clsMin, clsMax = 1, 3

import sys, os
from ROOT import *
from math import sqrt
from glob import glob
from RPCDPGAnalysis.SegmentAndTrackOnRPC.buildLabels import *

resultDir = "results/history"
if not os.path.exists(resultDir): os.makedirs(resultDir)

from RPCDPGAnalysis.SegmentAndTrackOnRPC.tdrstyle import set_tdr_style
set_tdr_style()

gStyle.SetOptStat(0)
gStyle.SetOptTitle(0)

gStyle.SetTitleSize(0.06, "X");
gStyle.SetTitleSize(0.06, "Y");

runs = []
avgClssB, avgClssE, avgClssRE4 = [], [], []

for fName in glob("data/cls/Run*/run*.txt"):
    if not os.path.exists(fName): continue
    run = int(os.path.basename(fName).split('.')[0][3:])
    runs.append(run)

    clssB, clssE, clssRE4 = [], [], []
    denB, denE, denRE4 = 0., 0., 0.
    for l in open(fName).readlines():
        l = l.strip()
        if len(l) == 0 or l[0] == '#': continue

        name, den, mean, err2 = l.split()
        den, mean, err2 = float(den), float(mean), float(err2)

        #if cls > 70 and den > 10:
        if den > 0:
            if name.startswith("W"):
                clssB.append(mean)
                denB += den
            elif name.startswith("RE+4") or name.startswith("RE-4"):
                clssRE4.append(mean)
                denRE4 += den
            else:
                clssE.append(mean)
                denE += den

    if denB == 0: avgClssB.append(-1)
    else: avgClssB.append(sum(clssB)/len(clssB))
    if denE  == 0: avgClssE.append(-1)
    else: avgClssE.append(sum(clssE)/len(clssE))
    if denRE4 == 0: avgClssRE4.append(-1)
    else: avgClssRE4.append(sum(clssRE4)/len(clssRE4))

nRuns = len(runs)
gapLS, gapTS = int(nRuns*0.1), int(nRuns*0.02)
periodsLS = {251168:"Run2015", 273150:"Run2016", 297050:"Run2017", 315488:"Run2018"}
periodsTS = {
    254277:"MD1", 257969:"MD2", 258287:"TS2",
    274954:"TS1", 277981:"MD1", 279588:"MD2", 281613:"MD3&TS2", 282708:"MD4",
    298996:"MD1&TS1", 300087:"MD2", 303824:"MD3&TS2",
    318733:"MD1&TS1", 321887:"MD2", 323414:"MD3&TS2",
}
gapTexts = []

nPoints = nRuns+(len(periodsLS)+1)*gapLS+len(periodsTS)*gapTS
hFrame = TH1F("hFrame", "hFrame;Run number;Cluster size", nPoints, 1, nPoints+1)
hFrame.SetMinimum(clsMin)
hFrame.SetMaximum(clsMax)
hFrame.GetYaxis().SetNdivisions(505)
hFrame.GetYaxis().SetTitleOffset(0.6)
hFrame.GetXaxis().SetBinLabel(1, "")
hFrame.GetXaxis().SetTickSize(0)
hFrame.GetXaxis().SetTitleOffset(1.8)

hLS = hFrame.Clone()
hTS = hFrame.Clone()
#hLS.SetFillStyle(3005)
#hTS.SetFillStyle(3005)
hLS.SetFillColor(TColor.GetColor("#CCCCCC"))
hTS.SetFillColor(TColor.GetColor("#EEEEEE"))
hLS.SetLineColor(TColor.GetColor("#CCCCCC"))
hTS.SetLineColor(TColor.GetColor("#EEEEEE"))
#hLS.SetLineWidth(0)
#hTS.SetLineWidth(0)

grpB, grpE, grpRE4 = TGraph(), TGraph(), TGraph()
ii = 0
for run, avgClsB, avgClsE, avgClsRE4 in sorted(zip(runs, avgClssB, avgClssE, avgClssRE4), key=lambda x: x[0]):
    ii += 1
    if run in periodsLS:
        for i in range(ii, ii+gapLS): hLS.Fill(i, 100)
        hFrame.GetXaxis().SetBinLabel(ii+gapLS, "%d" % run)

        #t = TText(ii+gapLS/2, clsMin+(clsMax-clsMin)*.1, "YETS")
        #t.SetTextAlign(12)
        #t.SetTextAngle(90)
        #t.SetTextSize(0.05)
        #gapTexts.append(t)

        #t = TText(ii+gapLS*1.05, clsMin+(clsMax-clsMin)*.02, periodsLS[run])
        t = TPaveText(ii+gapLS*1.05, clsMin, ii+gapLS*2.25, clsMin+(clsMax-clsMin)*.09, "")
        t.SetFillColor(kWhite)
        t.SetBorderSize(0)
        t.SetFillStyle(1001)
        t.SetTextAlign(11)
        t.SetTextSize(0.04)
        t.AddText(periodsLS[run])
        gapTexts.append(t)

        ii += gapLS
    elif run in periodsTS:
        for i in range(ii, ii+gapTS): hTS.Fill(i, 100)
        hFrame.GetXaxis().SetBinLabel(ii+gapTS, "%d" % run)

        t = TText(ii+gapTS/2, clsMin+(clsMax-clsMin)*.35, periodsTS[run])
        t.SetTextAlign(12)
        t.SetTextAngle(90)
        t.SetTextSize(0.025)
        gapTexts.append(t)
        ii += gapTS

    if avgClsB > 0: grpB.SetPoint(grpB.GetN(), ii, avgClsB)
    if avgClsE > 0: grpE.SetPoint(grpE.GetN(), ii, avgClsE)
    if avgClsRE4 > 0: grpRE4.SetPoint(grpRE4.GetN(), ii, avgClsRE4)

for i in range(ii+1, nPoints+1): hLS.Fill(i, 100)
#gapTexts[0].SetText(gapTexts[0].GetX(), gapTexts[0].GetY(), "LS1")
t = TText(gapLS/2, clsMin+(clsMax-clsMin)*.35, "LS1")
t.SetTextAlign(12)
t.SetTextAngle(90)
t.SetTextSize(0.05)
gapTexts.append(t)
t = TText(ii+gapLS/2, clsMin+(clsMax-clsMin)*.35, "LS2")
t.SetTextAlign(12)
t.SetTextAngle(90)
t.SetTextSize(0.05)
gapTexts.append(t)

grpB.SetMarkerStyle(26)
grpE.SetMarkerStyle(24)
grpRE4.SetMarkerStyle(25)

grpB.SetMarkerSize(.5)
grpE.SetMarkerSize(.5)
grpRE4.SetMarkerSize(.5)

grpB.SetMarkerColor(kRed)
grpE.SetMarkerColor(kBlue)
grpRE4.SetMarkerColor(kGreen+1)

grpB.SetLineColor(kRed)
grpE.SetLineColor(kBlue)
grpRE4.SetLineColor(kGreen+1)

c = TCanvas("cClsHistory", "cClsHistory", 1000, 450)
c.SetLeftMargin(0.08)
c.SetRightMargin(0.03)
c.SetTopMargin(0.1)
c.SetBottomMargin(0.25)

#leg = TLegend(992, 80, 1500, 87, "", "")
leg = TLegend(1-c.GetRightMargin()-0.1, c.GetBottomMargin(), 1-c.GetRightMargin(), c.GetBottomMargin()+0.2)
leg.SetBorderSize(0)
leg.SetFillStyle(1001)
leg.SetFillColor(kWhite)
leg.AddEntry(grpB, "Barrel", "lp")
leg.AddEntry(grpE, "RE1/2/3", "lp")
leg.AddEntry(grpRE4, "RE4", "lp")

hFrame.Draw()
hLS.Draw("histsame")
hTS.Draw("histsame")
grpRE4.Draw("p")
grpE.Draw("p")
grpB.Draw("p")
for t in gapTexts: t.Draw()
leg.Draw()
hFrame.Draw("axissame")

ll = buildLabel("", "outset")
ll[0].SetX(c.GetLeftMargin())
ll[0].SetY(1-c.GetTopMargin()+0.01)
ll[1].SetX(c.GetLeftMargin()+0.06)
ll[1].SetY(1-c.GetTopMargin()+0.01)
ll[2].SetX(1-c.GetRightMargin())
ll[2].SetY(1-c.GetTopMargin()+0.01)
for l in ll: l.Draw()

c.Print("%s/%s.png" % (resultDir, c.GetName()))
c.Print("%s/%s.pdf" % (resultDir, c.GetName()))
c.Print("%s/%s.C" % (resultDir, c.GetName()))


import numpy as np
from flask import Flask, request, render_template
import pickle

app = Flask(__name__)

model = pickle.load(open("../model/heart_failure_model.pkl", "rb"))

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/predict", methods=["POST"])
def predict():
    float_features=[float(x) for x in request.form.values()]
    final_features = [np.array(float_features)]
    prediction = model.predict(final_features)

    if prediction:
        output="You are in high risk of Heart Failure !! Consider consulting a cardiologist immediately"
    else:
        output="You are in low risk of Heart Failure Make sure to be fit with healthy diet and exercise"

    if float_features:
        return render_template("index.html", prediction_text=output)

if __name__ == "__main__":
    app.run(debug=True)


def divisorSum(n):
	x = list(x for tup in ([i, n//i] for i in range(1, int(n**0.5)+1) if n % i == 0) for x in tup)
	x.sort()
	x = x[:-1] #remove last element
	x = list(set(x))
	result = sum(x)
	return result

upperBound = 28124
abundantSums = [0 for x in range(2*upperBound)]
abundantIndex = []

for n in range(1, upperBound):
	result = divisorSum(n)
	if (result > n):
		abundantIndex.append(n)

for x in abundantIndex:
	for y in abundantIndex:
		abundantSums[x+y] = x+y

answer = 0
for n in range(1,upperBound):
	if (abundantSums[n] == 0):
		answer += n

print (answer)


'''
Created on 2021-12-27

@author: wf
'''
from OSMPythonTools.cachingStrategy import CachingStrategy, JSON
from OSMPythonTools.nominatim import Nominatim
from geopy.geocoders import Nominatim as GeoNominatim

from pathlib import Path
import os
import logging

class NominatimWrapper(object):
    '''
    Nominatim Wrapper to hide technical details of Nominatim interface
    '''

    def __init__(self, cacheDir:str=None,user_agent:str="ConferenceCorpus"):
        '''
        Constructor

            create a nominatim instance for the given cacheDir - if cacheDir is None use ~/.nominatim as cachedir

        Args:
            cacheDir(str): the path to the cache directory to be use by Noninatims JSON caching  Strategy
            user_agent(str): the user_agent to use for the geolocator

        '''
        if cacheDir is None:
            home = str(Path.home())
            cacheDir=f"{home}/.nominatim"
        self.cacheDir=cacheDir
        if not os.path.exists(self.cacheDir):
            os.makedirs(cacheDir)
        logging.getLogger('OSMPythonTools').setLevel(logging.ERROR)
        CachingStrategy.use(JSON, cacheDir=cacheDir)
        self.nominatim = Nominatim()
        self.geolocator = GeoNominatim(user_agent=user_agent)

    def lookupWikiDataId(self,locationText:str):
        '''
        lookup the Wikidata Identifier for the given locationText (if any)

        Args:
            locationText(str): the location text to search for

        Return:
            the wikidata Q identifier most fitting the given location text

        '''
        wikidataId=None
        nresult=self.nominatim.query(locationText,params={"extratags":"1"})
        nlod=nresult._json
        if len(nlod)>0:
            nrecord=nlod[0]
            if "extratags" in nrecord:
                extratags=nrecord["extratags"]
                if "wikidata" in extratags:
                    wikidataId=extratags["wikidata"]
        return wikidataId


from user_exceptions import *

def age_validation(age_input):
    '''This function validates the input of age. The function raises exceptions when th input is invalid.
    We assume the age range is [18,70]'''
    try:
        age_input =int(age_input)
        if (age_input < 18) or (age_input>70):
            raise out_of_range_age_exception
        else:
            return True
    except:
        return False
        raise invalid_age_exception

def education_validation(education_input):
    '''This function validates the input of education. The function raises exception when the input is invalid.'''
    education_input = ''.join(education_input.split())

    if education_input in ['Doctorate', 'Masters', 'Bachelors', 'Associate', 'Prof-school', 'Below 12th']:
        return True
    else:
        return False

def marital_validation(marital_input):
    '''This function validates the input of martial status.'''
    marital_input = ''.join(marital_input.split())
    if marital_input in ['Married', 'Married-spouse-absent', 'Separated', 'Divorced', 'Never-married', 'Widowed']:
        return True
    else:
        return False

def ocupation_validation(ocupation_input):
    '''This function validates the input of ocupation.'''
    ocupation_input = ''.join(ocupation_input.split())
    if ocupation_input in ['Adm-clerical', 'Armed-Forces', 'Craft-repair', 'Exec-managerial', 'Farming-fishing', 'Handlers-cleaners', 'Machine-op-inspct','Other-service', 'Priv-house-serv', 'Prof-specialty', 'Protective-serv','Sales', 'Tech-support', 'Transport-moving']:
        return True
    else:
        return False

def capital_gain_validation(capital_gain_input):
    '''
    This function validates the input of capital gain. This function raises exception when the input of capital gain is out of range.
    We assume the range is [0,100000]
    '''
    try:
        capital_gain_input =int(capital_gain_input)
        if (capital_gain_input < 0) or (capital_gain_input > 100000):
            raise out_of_range_capital_gain_exception
        else:
            return True
    except:
        return False
        raise invalid_capital_gain_exception

def hours_per_week_validation(hours_per_week_input):
    '''
    This function validates the input of hours per week. This function raises exception when the input of hours per week is out of range.
    We assume the range is [0,100]
    '''
    try:
        hours_per_week_input =int(hours_per_week_input)
        if (hours_per_week_input < 0) or (hours_per_week_input > 100):
            raise out_of_range_capital_gain_exception
        else:
            return True
    except:
        return False
        raise invalid_hours_per_week_exception

class parse_func:
    '''
    this class creates a string object and has different methods for parsing the string object into data to be processed in prediction model
    '''
    def __init__(self):
        '''
        initiate the parse function class
        '''
        pass

    def parse_age(self, string):
        '''
        this function parses age string into integer
        '''
        return int(string)

    def parse_education(self, string):
        '''
        this function parses education string into a numerical value, representing categorical level of education
        '''
        if string == 'Doctorate':
            return 1
        elif string == 'Masters':
            return 2
        elif string == 'Bachelors':
            return 3
        elif string == 'Associate':
            return 4
        elif string == 'Prof-school':
            return 5
        elif string == 'Below 12th':
            return 6
        else:
            raise unable_to_parse_exception()

    def parse_marital_status(self, string):
        '''
        this function parses marital status string into a numerical value, representing categorical level of marital status
        '''
        if string == 'Married':
            return 1
        elif string == 'Married-spouse-absent':
            return 2
        elif string == 'Never-married':
            return 3
        elif string == 'Widowed':
            return 4
        else:
            raise unable_to_parse_exception()

    def parse_ocupation(self, string):
        '''
        this function parses ocupation string into a numerical value, representing categorical level of ocupation
        '''
        if string == 'Adm-clerical':
            return 0
        elif string == 'Armed-Forces':
            return 1
        elif string == 'Craft-repair':
            return 2
        elif string == 'Exec-managerial':
            return 3
        elif string == 'Farming-fishing':
            return 4
        elif string == 'Handlers-cleaners':
            return 5
        elif string == 'Machine-op-inspct':
            return 6
        elif string == 'Other-service':
            return 7
        elif string == 'Priv-house-serv':
            return 8
        elif string == 'Prof-specialty':
            return 9
        elif string == 'Protective-serv':
            return 10
        elif string == 'Sales':
            return 11
        elif string == 'Tech-support':
            return 12
        elif string == 'Transport-moving':
            return 13
        else:
            raise unable_to_parse_exception()

    def parse_capital_gain(self, string):
        '''
        this function parses capital gain string into integer
        '''
        return int(string)

    def parse_hours_per_week(self, string):
        '''
        this function parses hours per week string into integer
        '''
        return int(string)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot plastic fluxes to Seychelles by country and sink location
@author: Noam Vogt-Vincent
"""

### TO DO!!!!!
# Sources are currently excluded if they are not in the top X in a source, but are
# in others (should be included)

import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cmasher as cmr
import matplotlib.colors as colors
import matplotlib.ticker as mticker
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from netCDF4 import Dataset
from glob import glob

##############################################################################
# DIRECTORIES & PARAMETERS                                                   #
##############################################################################

# PARAMETERS
param = {# Analysis parameters
         'ls_d': 3650,      # Sinking timescale (days)
         'lb_d': 40,        # Beaching timescale (days)
         'title': 'Debris sources for zero windage, l(s)=10a, l(b)=20d',

         # Bounds
         'lon_west': 20,
         'lon_east': 130,
         'lat_south': -40,
         'lat_north': 30,
         }

# DIRECTORIES
dirs = {'script': os.path.dirname(os.path.realpath(__file__)),
        'plastic': os.path.dirname(os.path.realpath(__file__)) + '/../PLASTIC_DATA/',
        'grid': os.path.dirname(os.path.realpath(__file__)) + '/../GRID_DATA/',
        'traj': os.path.dirname(os.path.realpath(__file__)) + '/../TRAJ/',
        'fig': os.path.dirname(os.path.realpath(__file__)) + '/../FIGURES/'}

# FILE HANDLES
fh = {'sink_list': dirs['plastic'] + 'sink_list.in',
      'grid':    dirs['grid'] + 'griddata.nc',
      'fig': dirs['fig'] + 'marine_plastic_sources_' + str(param['ls_d']) + '_b' + str(param['lb_d']),
      'data': sorted(glob(dirs['traj'] + 'marine_data_s' + str(param['ls_d']) + '_b' + str(param['lb_d']) + '*.pkl')),
      'cmap': dirs['fig'] + 'cmap_data.pkl'}

##############################################################################
# CALCULATE FLUXES                                                           #
##############################################################################

sink_list = pd.read_csv(fh['sink_list'])
nsink = np.shape(sink_list)[0]

# Grid accumulating fluxes by sink site
# Firstly construct grid
with Dataset(fh['grid'], mode='r') as nc:
    lon = nc.variables['lon_psi'][:]
    lat = nc.variables['lat_psi'][:]
    lon_bnd = np.concatenate([nc.variables['lon_rho'][:], [180]])
    lat_bnd = nc.variables['lat_rho'][:]

    lon = lon[(lon >= param['lon_west'])*(lon <= param['lon_east'])]
    lat = lat[(lat >= param['lat_south'])*(lat <= param['lat_north'])]
    lon_bnd = lon_bnd[(lon_bnd >= param['lon_west'])*(lon_bnd <= param['lon_east'])]
    lat_bnd = lat_bnd[(lat_bnd >= param['lat_south'])*(lat_bnd <= param['lat_north'])]

# Create empty grids for gridding
grid = np.zeros((nsink, len(lat), len(lon)))

for data_fh in fh['data']:
    # if data_fh != fh['data'][0]: # TEMPORARY TIME SAVING HACK, REMOVE!
    #     break

    data = pd.read_pickle(data_fh)
    print(data_fh)

    for sinkidx, sink in enumerate(sink_list['Sink code']):
        # Filter by sink site
        data_sink = data.loc[data['sink_id'] == sink]
        print(sinkidx)

        grid[sinkidx, :, :] += np.histogram2d(data_sink['lon0'].values,
                                              data_sink['lat0'].values,
                                              bins=[lon_bnd, lat_bnd],
                                              weights=data_sink['plastic_flux'].values)[0].T

##############################################################################
# PLOT                                                                       #
##############################################################################

f, ax = plt.subplots(1, 1, figsize=(20, 12), constrained_layout=True,
                     subplot_kw={'projection': ccrs.PlateCarree()})
plt.subplots_adjust(bottom=0, top=1)

data_crs = ccrs.PlateCarree()

mass_flux = ax.pcolormesh(lon_bnd, lat_bnd, np.sum(grid[:,:,:], axis=0)/(len(fh['data'])*1728),
                          norm=colors.LogNorm(vmin=1e-5, vmax=1e-2), cmap=cmr.torch, transform=data_crs)
# Multiplication by years * months per year * particles released per cell per month

ax.spines['geo'].set_linewidth(1)
ax.set_ylabel('Latitude')
ax.set_xlabel('Longitude')
ax.set_aspect('equal')
# ax.set_title('Fraction of mass from cell beaching at Seychelles')

cax1 = f.add_axes([ax.get_position().x1+0.0105,ax.get_position().y0,0.015,ax.get_position().height])

cb1 = plt.colorbar(mass_flux, cax=cax1, pad=0.1)
cb1.set_label('Fraction of mass from cell beaching at Seychelles', size=12)

land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m',
                                        edgecolor='white', linewidth=0.5,
                                        facecolor='black')
ax.add_feature(land_10m)

gl = ax.gridlines(crs=data_crs, draw_labels=True, linewidth=1, color='black', linestyle='-')
gl.xlocator = mticker.FixedLocator(np.arange(20, 140, 20))
gl.ylocator = mticker.FixedLocator(np.arange(-40, 40, 20))
gl.ylabels_right = False
gl.xlabels_top = False

plt.savefig(fh['fig'] + '_all.png', dpi=300, bbox_inches='tight')

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

f, ax = plt.subplots(1, 1, figsize=(20, 12), constrained_layout=True,
                     subplot_kw={'projection': ccrs.PlateCarree()})
plt.subplots_adjust(bottom=0, top=1)

data_crs = ccrs.PlateCarree()

mass_flux = ax.pcolormesh(lon_bnd, lat_bnd, np.sum(grid[:4,:,:], axis=0)/(len(fh['data'])*1728),
                          norm=colors.LogNorm(vmin=1e-5, vmax=1e-2), cmap=cmr.torch, transform=data_crs)
# Multiplication by years * months per year * particles released per cell per month

ax.spines['geo'].set_linewidth(1)
ax.set_ylabel('Latitude')
ax.set_xlabel('Longitude')
ax.set_aspect('equal')
# ax.set_title('Fraction of mass from cell beaching at Seychelles')

cax1 = f.add_axes([ax.get_position().x1+0.0105,ax.get_position().y0,0.015,ax.get_position().height])

cb1 = plt.colorbar(mass_flux, cax=cax1, pad=0.1)
cb1.set_label('Fraction of mass from cell beaching at the Aldabra Group', size=12)

land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m',
                                        edgecolor='white', linewidth=0.5,
                                        facecolor='black')
ax.add_feature(land_10m)

gl = ax.gridlines(crs=data_crs, draw_labels=True, linewidth=1, color='black', linestyle='-')
gl.xlocator = mticker.FixedLocator(np.arange(20, 140, 20))
gl.ylocator = mticker.FixedLocator(np.arange(-40, 40, 20))
gl.ylabels_right = False
gl.xlabels_top = False

plt.savefig(fh['fig'] + '_AldabraGrp.png', dpi=300, bbox_inches='tight')

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

f, ax = plt.subplots(1, 1, figsize=(20, 12), constrained_layout=True,
                     subplot_kw={'projection': ccrs.PlateCarree()})
plt.subplots_adjust(bottom=0, top=1)

data_crs = ccrs.PlateCarree()

mass_flux = ax.pcolormesh(lon_bnd, lat_bnd, np.sum(grid[12:,:,:], axis=0)/(len(fh['data'])*1728),
                          norm=colors.LogNorm(vmin=1e-5, vmax=1e-2), cmap=cmr.torch, transform=data_crs)
# Multiplication by years * months per year * particles released per cell per month

ax.spines['geo'].set_linewidth(1)
ax.set_ylabel('Latitude')
ax.set_xlabel('Longitude')
ax.set_aspect('equal')
# ax.set_title('Fraction of mass from cell beaching at Seychelles')

cax1 = f.add_axes([ax.get_position().x1+0.0105,ax.get_position().y0,0.015,ax.get_position().height])

cb1 = plt.colorbar(mass_flux, cax=cax1, pad=0.1)
cb1.set_label('Fraction of mass from cell beaching at the Seychelles Plateau', size=12)

land_10m = cfeature.NaturalEarthFeature('physical', 'land', '10m',
                                        edgecolor='white', linewidth=0.5,
                                        facecolor='black')
ax.add_feature(land_10m)

gl = ax.gridlines(crs=data_crs, draw_labels=True, linewidth=1, color='black', linestyle='-')
gl.xlocator = mticker.FixedLocator(np.arange(20, 140, 20))
gl.ylocator = mticker.FixedLocator(np.arange(-40, 40, 20))
gl.ylabels_right = False
gl.xlabels_top = False

plt.savefig(fh['fig'] + '_SeychellesPlateau.png', dpi=300, bbox_inches='tight')


#이항계수 최적화 알고리즘
def bin3(n,k,MAX):
    if(k > n //2):
        k = n -k

    B = [0]*(k +1) #크기가 k인 배열에 값을 0으로 초기화
    B[0] =1

    for i in range(1, n+1):
        j = min(i,k)
        while (j > 0):
            B[j] = (B[j] + B[j-1]) % MAX
            j-=1
    return B[k]

n,k,MAX = map(int,input().split()) #정수 한꺼번에 받기
#print("{0} + {1} ={2}".format(n,k, n+k))
print(bin3(n,k,MAX))


"""
# @Time : 2022/12/5 14:35
# @Author : ruetrash
# @File : AlexNet_server.py
"""

import torch
import TCP.tcp as tcp
from ProtocolOnRing.secret_sharing_fixpoint import ShareFloat
from ModelAndLayers.AlexNetAndMnist import AlexNet
import ProtocolOnRing.secret_sharing_fixpoint as ssf
from ModelAndLayers.onnx_converter import onnx_converter

# 初始化参数
server = tcp.TCPServer("127.0.0.1", 9999, 40960)
server.run()
p = 0

device = "cpu"

net = AlexNet.AlexNet()
net.load_state_dict(torch.load('ModelAndLayers/AlexNetAndMnist/MNIST_bak.pkl'))
# secure_model = buildSecureModelProcessOnServer(model=net, server=server)
dummy_input = torch.ones(100, 1, 28, 28)
secure_model = onnx_converter.from_pytorch(net, dummy_input, party=server, device=device)

while 1:
    img_0 = server.receive_torch_array(device)
    input_image = ShareFloat(img_0, p, server, device)

    secure_model.set_input(input_image)
    secure_model.predict()

    output = secure_model.output['output']
    res_ = ssf.restore_float(output)
    # res_ = ssf.restore_float(secure_model.input)
    res = ssf.decode(res_)


from django.db import models
import uuid

class Character(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
    name = models.CharField(max_length=20, unique=True)
    level = models.PositiveIntegerField()
    silver = models.PositiveIntegerField()
    gold = models.PositiveIntegerField()

    char_class = models.ForeignKey(
        "classes.Class",
        on_delete=models.CASCADE,
        related_name="char_class",
    )

    equipments = models.ManyToManyField(
        "equipments.Equipment",
        related_name="equipments"
    )

    skills = models.ManyToManyField(
        "skills.Skill",
        related_name="skills"
    )

    user = models.OneToOneField(
        "users.User",
        on_delete=models.CASCADE,
        related_name="user_char"
    )


# -*- coding: utf-8 -*-
import flask
import telebot

from time import sleep

from poems import find_rhyme

try:
    import conf
except ImportError:
    import os

    conf = type(
        "conf",
        (),
        {
            "TOKEN": os.environ["TOKEN"],
            "WEBHOOK_HOST": os.environ["WEBHOOK_HOST"],
            "WEBHOOK_PORT": os.environ["WEBHOOK_PORT"],
        },
    )

WEBHOOK_URL_BASE = "https://{}:{}".format(conf.WEBHOOK_HOST, conf.WEBHOOK_PORT)
WEBHOOK_URL_PATH = "/{}/".format(conf.TOKEN)

bot = telebot.TeleBot(conf.TOKEN)
sleep(1)
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH)

app = flask.Flask(__name__)

@bot.message_handler(commands=["start", "help"])
def send_welcome(message):
    bot.send_message(
        message.chat.id,
        "Это бот, который подбирает рифму на ваше сообщение. За основу берутся строчки из https://github.com/IlyaGusev/PoetryCorpus.",
    )

@bot.message_handler(func=lambda m: True)
def send_len(message):
    text = message.text
    chat_id = message.chat.id

    rhyme = find_rhyme(text)
    bot.send_message(chat_id, rhyme)

@app.route("/", methods=["GET", "HEAD"])
def index():
    return "ok"

@app.route(WEBHOOK_URL_PATH, methods=["POST"])
def webhook():
    if flask.request.headers.get("content-type") == "application/json":
        json_string = flask.request.get_data().decode("utf-8")
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return ""
    else:
        flask.abort(403)

if __name__ == "__main__":
    import os

    app.debug = True
    port = int(os.environ.get("PORT", 5000))
    app.run(host="0.0.0.0", port=port)


from functools import partial
from typing import Any, Iterable, List, Type, Optional
import contextlib
from collections import defaultdict, OrderedDict

import numpy as np
import dask
from dask import delayed
import dask.array as da

from libertem.io.corrections import CorrectionSet
from libertem.io.dataset.base import DataSet
from libertem.utils.devices import detect

from .base import BaseJobExecutor
from libertem.common.executor import Environment, TaskCommHandler, TaskProtocol
from libertem.common.scheduler import Worker, WorkerSet

from ..common.buffers import BufferWrapper
from ..common.math import prod
from ..udf.base import (
    UDFMergeAllMixin, UDFRunner, UDF, UDFData, MergeAttrMapping,
    get_resources_for_backends, UDFResults, BackendSpec
)

from .utils.dask_buffer import DaskBufferWrapper, DaskPreallocBufferWrapper, DaskResultBufferWrapper
from .utils import delayed_unpack

class DelayedUDFRunner(UDFRunner):
    def __init__(self, udfs: List[UDF], debug: bool = False, progress_reporter: Any = None):
        self._part_results = defaultdict(lambda: {})
        super().__init__(udfs, debug=debug)

    @staticmethod
    def _make_udf_result(udfs: Iterable[UDF], damage: BufferWrapper) -> "UDFResults":
        udf_results = UDFRunner._make_udf_result(udfs, damage)
        buffers = udf_results.buffers
        damage = udf_results.damage
        new_buffers = tuple(
            {
                k: DaskResultBufferWrapper.from_buffer_wrapper(v)
                for k, v in bufs.items()
            }
            for bufs in buffers
        )
        return UDFResults(
            buffers=new_buffers,
            damage=damage,
        )

    def _apply_part_result(self, udfs: Iterable[UDF], damage, part_results, task):
        for part_results_udf, udf in zip(part_results, udfs):
            # Allow user to define an alternative merge strategy
            # using dask-compatible functions. In the Delayed case we
            # won't be getting partial results with damage anyway.
            # Currently there is no interface to provide all of the results
            # to udf.merge at once and in the correct order, so I am accumulating
            # results in self._part_results[udf] = {partition_slice_roi: part_results, ...}
            if (isinstance(udf, UDFMergeAllMixin)
                    or (type(udf).merge is UDF.merge and not udf.requires_custom_merge_all)):
                if self._accumulate_part_results(udf, part_results_udf, task):
                    try:
                        parts = {
                            key: value.get_proxy()
                            for key, value in self._part_results[udf].items()
                        }
                        udf._do_merge_all(parts)
                    finally:
                        self._part_results.pop(udf, None)
                continue

            # In principle we can requrire that sig merges are done sequentially
            # by using dask.graph_manipulation.bind, this could improve thread
            # safety on the sig buffer. In the current implem it's not necessary as
            # we are calling delayed_apply_part_result sequentially on results
            # and replacing all buffers with their partially merged versions
            # on each call, so we are implicitly sequential when updating
            # try:
            #     bind_to = udf.prior_merge
            # except AttributeError:
            #     bind_to = None

            structure = structure_from_task([udf], task)[0]
            flat_structure = delayed_unpack.flatten_nested(structure)
            flat_mapping = delayed_unpack.build_mapping(structure)

            src = part_results_udf.get_proxy()
            src_dict = {k: b for k, b in src._dict.items()}

            dest_dict = {}
            for k, b_decl in udf.get_result_buffers().items():
                # We skip result_only buffers since they are not expected
                # in the dest_dict by the default merge function
                if b_decl.use == 'result_only':
                    continue
                b = udf.results.get_buffer(k)
                view = b.get_view_for_partition(task.partition)
                # Handle result-only buffers
                if view is not None:
                    try:
                        dest_dict[k] = view.unwrap_sliced()
                    except AttributeError:
                        # Handle kind='single' buffers
                        # Could handle sig buffers this way too if we assert no chunking
                        dest_dict[k] = view

            # Run the udf.merge function in a wrapper which flattens
            # the results to a flat list which can be unpacked from the Delayed
            # This step makes a copy of the buffer view inside the delayed
            # call because this default Dask behaviour is to give a read-only
            # view of the arguments to the delayed function
            merged_del = delayed(merge_wrap, nout=len(flat_mapping))
            merged_del_result = merged_del(udf, dest_dict, src_dict)

            # The following is needed when binding sequential updates on sig buffers
            # if bind_to is not None:
            #     merged_del = delayed_bind([*merged_del_result],
            #                               [*bind_to])
            # if any([b.kind != 'nav' for _, b in udf.results.items()]):
            #     # have sig result, gotta do a bind merge next time round
            #     udf.prior_merge = merged_del_result

            # We now build the result back into dask arrays and assign them
            # into the appropriate slices of the full result buffers
            wrapped_res = delayed_to_buffer_wrappers(merged_del_result, flat_structure,
                                                     task.partition, as_buffer=False)
            renested = delayed_unpack.rebuild_nested(wrapped_res, flat_mapping)

            # Assign into the result buffers with the partially merged version
            # This is OK because we are calling this part merge function sequentially
            # so each new call gets the most recent version of the buffer in the
            # dask task graph
            udf.set_views_for_partition(task.partition)
            dest = udf.results.get_proxy()
            merged = MergeAttrMapping(renested)
            for k in dest:
                getattr(dest, k)[:] = getattr(merged, k)

        v = damage.get_view_for_partition(task.partition)
        v[:] = True

    def _accumulate_part_results(self, udf, part_results, task):
        """
        If the udf has a merge_all method, this function is used
        to accumulate dask array-backed partial results on the executor
        so that the merge_all can be called on all of them at once

        Ensures that the results are correctly ordered and complete
        before allowing merge_all to be called
        """
        buf = next(iter(part_results.values()))  # get the first buffer
        slice_with_roi = buf._slice_for_partition(task.partition)
        self._part_results[udf][slice_with_roi] = part_results

        # number of frames in dataset
        if udf.meta.roi is not None:
            target_coverage = np.count_nonzero(udf.meta.roi)
        else:
            target_coverage = prod(task.partition.meta.shape.nav)
        # number of frames we have results for
        current_coverage = sum(prod(k.shape.nav) for k in self._part_results[udf].keys())
        if target_coverage == current_coverage:
            ordered_results = sorted(self._part_results[udf].items(),
                                     key=lambda kv: kv[0].origin[0])
            self._part_results[udf] = OrderedDict(ordered_results)
            return True
        elif current_coverage > target_coverage:
            raise RuntimeError('More frames accumulated than ROI specifies - '
                              f'target {target_coverage} - processed {current_coverage}')
        return False

    def results_for_dataset_sync(self, dataset: DataSet, executor: 'DelayedJobExecutor',
            roi: Optional[np.ndarray] = None, progress: bool = False,
            corrections: Optional[CorrectionSet] = None, backends: Optional[BackendSpec] = None,
            dry: bool = False) -> Iterable[tuple]:

        executor.register_master_udfs(self._udfs)

        return super().results_for_dataset_sync(
            dataset, executor, roi=roi, progress=progress,
            corrections=corrections, backends=backends, dry=dry
        )

class DelayedJobExecutor(BaseJobExecutor):
    """
    :class:`~libertem.common.executor.JobExecutor` that uses dask.delayed to execute tasks.

    .. versionadded:: 0.9.0

    Highly experimental at this time!
    """
    def __init__(self):
        # Only import if actually instantiated, i.e. will likely be used
        import libertem.preload  # noqa: 401
        self._udfs = None

    @contextlib.contextmanager
    def scatter(self, obj):
        yield delayed(obj)

    def cancel(self, cancel_id: Any):
        pass

    def run_tasks(
        self,
        tasks: Iterable[TaskProtocol],
        params_handle: Any,
        cancel_id: Any,
        task_comm_handler: TaskCommHandler,
    ):
        """
        Wraps the call task() such that it returns a flat list
        of results, then unpacks the Delayed return value into
        the normal

            :code:`tuple(udf.results for udf in self._udfs)`

        where the buffers inside udf.results are dask arrays instead
        of normal np.arrays

        Needs a reference to the udfs on the master node so
        that the results structure can be inferred. This reference is
        found in self._udfs, which is set with the method:

            :code:`executor.register_master_udfs(udfs)`

        called from :meth:`DelayedUDFRunner.results_for_dataset_sync`
        """
        env = Environment(threads_per_worker=1, threaded_executor=True)
        for task in tasks:
            structure = structure_from_task(self._udfs, task)
            flat_structure = delayed_unpack.flatten_nested(structure)
            flat_mapping = delayed_unpack.build_mapping(structure)
            flat_result_task = partial(task_wrap, task)
            result = delayed(flat_result_task, nout=len(flat_structure))(env=env,
                                                                         params=params_handle)
            wrapped_res = delayed_to_buffer_wrappers(result, flat_structure, task.partition,
                                                     roi=self._udfs[0].meta.roi)
            renested = delayed_unpack.rebuild_nested(wrapped_res, flat_mapping)
            result = tuple(UDFData(data=res) for res in renested)
            yield result, task

    def run_function(self, fn, *args, **kwargs):
        result = fn(*args, **kwargs)
        return result

    def run_delayed(self, fn, *args, _delayed_kwargs=None, **kwargs):
        if _delayed_kwargs is None:
            _delayed_kwargs = {}
        result = delayed(fn, **_delayed_kwargs)(*args, **kwargs)
        return result

    def map(self, fn, iterable):
        return [fn(item)
                for item in iterable]

    def run_each_host(self, fn, *args, **kwargs):
        return {"localhost": fn(*args, **kwargs)}

    def run_each_worker(self, fn, *args, **kwargs):
        return {"delayed": fn(*args, **kwargs)}

    def get_available_workers(self):
        resources = {"compute": 1, "CPU": 1}
        # We don't know at this time,
        # but assume one worker per CPU
        devices = detect()
        return WorkerSet([
            Worker(
                name='delayed', host='localhost',
                resources=resources,
                nthreads=len(devices['cpus']),
            )
        ])

    def modify_buffer_type(self, buf):
        """
        Convert existing buffers from BufferWrapper to DaskBufferWrapper

        A refactoring of the UDF backend would remove the need for this method.

        :meta private:
        """
        return DaskBufferWrapper.from_buffer(buf)

    def register_master_udfs(self, udfs):
        """
        Give the executor a reference to the udfs instantiated
        on the main node, for introspection purposes

        :meta private:
        """
        self._udfs = udfs

    def _compute(self, *args, udfs=None, user_backends=None, traverse=True, **kwargs):
        """
        Acts as dask.compute(*args, **kwargs) but with knowledge
        of Libertem data structures and compute resources
        """
        if 'resources' in kwargs:
            if udfs is not None:
                raise ValueError('Cannot specify both udfs for resources and resources to use')
            resources = kwargs.get('resources')
        elif udfs is not None:
            resources = self.get_resources(udfs, user_backends=user_backends)
        else:
            resources = None
        kwargs['resources'] = resources

        to_unpack = tuple(a for a in args)
        unwrapped_args = tuple(self.unwrap_results(a) for a in to_unpack)
        results = dask.compute(*unwrapped_args, traverse=traverse, **kwargs)
        if len(args) == 1:
            if len(results) > 1:
                raise RuntimeWarning(f'Unexpected number of results {len(results)} '
                                     'from dask.compute, dropping extras')
            results = results[0]
        return results

    @staticmethod
    def get_resources_from_udfs(udfs, user_backends=None):
        """
        Returns the resources required by the udfs passed as
        argument, excluding those not in the tuple user_backends
        """
        if user_backends is None:
            user_backends = tuple()
        if isinstance(udfs, UDF):
            udfs = [udfs]
        backends = [udf.get_backends() for udf in udfs]
        return get_resources_for_backends(backends, user_backends)

    @staticmethod
    def unwrap_results(results):
        unpackable = {**delayed_unpack.default_unpackable(),
                      UDFData: lambda x: x._data.items(),
                      DaskPreallocBufferWrapper: lambda x: [(0, x.data)],
                      DaskBufferWrapper: lambda x: [(0, x.data)],
                      }

        res_unpack = delayed_unpack.flatten_nested(results, unpackable_types=unpackable)
        flat_mapping = delayed_unpack.build_mapping(results, unpackable_types=unpackable)
        flat_mapping_reduced = [el[:-1] if issubclass(el[-1][0], BufferWrapper) else el
                                for el in flat_mapping]
        return delayed_unpack.rebuild_nested(res_unpack, flat_mapping_reduced)

    def get_udf_runner(self) -> Type['UDFRunner']:
        return DelayedUDFRunner

def make_copy(array_dict):
    for k, v in array_dict.items():
        if not v.flags['WRITEABLE']:
            array_dict[k] = v.copy()
    return array_dict

def merge_wrap(udf, dest_dict, src_dict):
    """
    The function called as delayed, acting as a wrapper
    to return a flat list of results rather than a structure
    of UDFData or MergeAttrMapping

    :meta private:
    """
    # Have to make a copy of dest buffers because Dask brings
    # data into the delayed function as read-only np arrays
    # I experimented with setting WRITEABLE to True but this
    # resulted in errors in the final array
    dest_dict = make_copy(dest_dict)

    dest = MergeAttrMapping(dest_dict)
    src = MergeAttrMapping(src_dict)

    # In place merge into the copy of dest
    udf.merge(dest=dest, src=src)
    # Return flat list of results so they can be unpacked later
    return delayed_unpack.flatten_nested(dest._dict)

def task_wrap(task, *args, **kwargs):
    """
    Flatten the structure tuple(udf.results for udf in self._udfs)
    where udf.results is an instance of UDFData(data={'name':BufferWrapper,...})
    into a simple list [np.ndarray, np.ndarray, ...]

    :meta private:
    """
    res = task(*args, **kwargs)
    res = tuple(r._data for r in res)
    flat_res = delayed_unpack.flatten_nested(res)
    return [r._data for r in flat_res]

def structure_from_task(udfs, task):
    """
    Based on the instantiated whole dataset UDFs and the task
    information, build a description of the expected UDF results
    for the task's partition like:

    :code:`({'buffer_name': StructDescriptor(shape, dtype, extra_shape, buffer_kind), ...}, ...)`

    :meta private:
    """
    structure = []
    for udf in udfs:
        res_data = {}
        for buffer_name, buffer in udf.results.items():
            part_buf_extra_shape = buffer.extra_shape
            buffer.set_shape_partition(task.partition, roi=buffer._roi)
            part_buf_shape = buffer.shape
            part_buf_dtype = buffer.dtype
            res_data[buffer_name] = \
                delayed_unpack.StructDescriptor(np.ndarray,
                                                shape=part_buf_shape,
                                                dtype=part_buf_dtype,
                                                kind=buffer.kind,
                                                extra_shape=part_buf_extra_shape)
        results_container = res_data
        structure.append(results_container)
    return tuple(structure)

def delayed_to_buffer_wrappers(flat_delayed, flat_structure, partition, roi=None, as_buffer=True):
    """
    Take the iterable Delayed results object, and re-wrap each Delayed object
    back into a BufferWrapper wrapping a dask.array of the correct shape and dtype

    :meta private:
    """
    wrapped_res = []
    for el, descriptor in zip(flat_delayed, flat_structure):
        buffer_kind = descriptor.kwargs.pop('kind')
        extra_shape = descriptor.kwargs.pop('extra_shape')
        buffer_dask = da.from_delayed(el, *descriptor.args, **descriptor.kwargs)
        if as_buffer:
            buffer = DaskBufferWrapper(buffer_kind,
                                       extra_shape=extra_shape,
                                       dtype=descriptor.kwargs['dtype'])
            # Need to test whether roi=None here is a problem
            buffer.set_shape_partition(partition, roi=roi)
            buffer.replace_array(buffer_dask)
            wrapped_res.append(buffer)
        else:
            wrapped_res.append(buffer_dask)
    return wrapped_res


import logging
from math import ceil

from matplotlib import pyplot as plt
from matplotlib import colors
import matplotlib.patches as patches
import numpy as np

from am.segment.image_utils import overlay_source_mask
from am.utils import min_max, time_it

logger = logging.getLogger('am-segm')

def cut_patch(image, y_offset=0, x_offset=0, patch=1000):
    return image[y_offset:y_offset+patch, x_offset:x_offset+patch]

def plot_image(image, figsize=(16, 10), dpi=100, **kwargs):
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)
    ax.imshow(image, **kwargs)
    return fig, ax

def plot_axis_hist(axis_hist, axis_coords, labels, uniq_labels):
    fig, ax = plt.subplots(1, 1, figsize=(20, 10))
    ax.plot(np.arange(axis_hist.shape[0]), axis_hist, c='black')

    norm = colors.Normalize(vmin=min(uniq_labels), vmax=max(uniq_labels))
    cmap = plt.cm.get_cmap('jet', len(uniq_labels))
    for label in uniq_labels:
        x_min, x_max = min_max(axis_coords[labels == label])
        y_min, y_max = min_max(axis_hist)

        rect = patches.Rectangle(xy=(x_min, y_min),
                                 width=x_max - x_min, height=y_max - y_min,
                                 color=cmap(norm(label)))
        ax.add_patch(rect)

def plot_labels(ax, image, target_axis, axis_coords, labels, uniq_labels):
    norm = colors.Normalize(vmin=min(uniq_labels), vmax=max(uniq_labels))
    cmap = plt.cm.get_cmap('jet', len(uniq_labels))
    for label in uniq_labels:
        if target_axis == 1:
            x_min, x_max = min_max(axis_coords[labels == label])
            y_min, y_max = (0, image.shape[0])
        else:
            x_min, x_max = (0, image.shape[1])
            y_min, y_max = min_max(axis_coords[labels == label])

        rect = patches.Rectangle(xy=(x_min, y_min),
                                 width=x_max - x_min, height=y_max - y_min,
                                 alpha=0.4, color=cmap(norm(label)))
        ax.add_patch(rect)

def plot_image_label_overlay(image, target_axis, axis_coords, labels, uniq_labels):
    fig, ax = plt.subplots(1, 1, figsize=(10, 10))
    ax.imshow(image, cmap='gray', alpha=0.6)
    plot_labels(image, ax, target_axis, axis_coords, labels, uniq_labels)

def shift_center_coords(centers, indices, row_offset, col_offset, patch_size):
    mask = (row_offset < centers[:, 0]) & (centers[:, 0] < row_offset + patch_size) &\
           (col_offset < centers[:, 1]) & (centers[:, 1] < col_offset + patch_size)
    shifted_centers = centers[mask]
    shifted_centers[:, 0] -= row_offset
    shifted_centers[:, 1] -= col_offset
    return shifted_centers, indices[mask]

@time_it
def plot_am_labels(
    mask, centers, labels, source=None, row_offset=None, col_offset=None, patch_size=None
):
    if patch_size:
        centers, labels = shift_center_coords(centers, labels, row_offset, col_offset, patch_size)
        mask = mask[row_offset : (row_offset + patch_size), col_offset : (col_offset + patch_size)]
        if source is not None:
            source = source[
                row_offset : (row_offset + patch_size), col_offset : (col_offset + patch_size)
            ]

    dpi = 100
    figsize = (ceil(mask.shape[1] / dpi), ceil(mask.shape[0] / dpi))
    fig, ax = plt.subplots(figsize=figsize, dpi=dpi)

    overlay = overlay_source_mask(source, mask)
    ax.imshow(np.array(overlay), cmap='viridis', interpolation=None)

    circle_size = (3 * 72 / fig.dpi) ** 2  # circle size (diameter**2) in points
    fontsize = 7.5 * 72 / fig.dpi  # text size in points
    ys, xs = zip(*centers)
    ax.scatter(xs, ys, color='green', s=circle_size, linewidth=0)
    for (y, x), label in zip(centers, labels):
        ax.text(x, y, str(label), color='blue', fontsize=fontsize)

@time_it
def overlay_image_with_am_labels(source, mask, am_centers, acq_indices, path):
    logger.info(f'Overlaying image with AM labels and saving at {path}')
    plot_am_labels(mask=mask, centers=am_centers, labels=acq_indices, source=source)
    plt.axis('off')
    plt.savefig(path, bbox_inches='tight')
    plt.close()

def plot_coord_peaks(hist, peaks, height=None):
    fig, ax = plt.subplots(figsize=(15, 5))
    ax.plot(hist)
    ax.plot(peaks, hist[peaks], 'x')
    if height:
        ax.plot(np.ones_like(hist) * height, '--')


import os
import datetime

TESTS_PATH = os.path.dirname(__file__)
SECONDS_PER_DAY = 30 * 60 + 23 * 3600

# twitter dataset extracted from
path = os.path.join(TESTS_PATH, "workload.txt")

def get_workload():
    with open(path, "r") as f:
        data = f.read()
        workload = data.split(" ")
        return_workload = []
        for i, w in enumerate(workload):
            try:
                return_workload.append(int(w))
            except:
                pass
        return return_workload

def parse_date_str(date_str):
    parts = list(map(int, date_str.split(":")))
    if len(parts) == 3:
        # day:hour:minute format
        day, hour, minute = parts
        return datetime.datetime(2023, 1, day, hour, minute)
    else:
        # day:hour:minute:second format
        day, hour, minute, second = parts
        return datetime.datetime(2023, 1, day, hour, minute, second)

def twitter_workload_generator(days, damping_factor=None):
    workload_all = get_workload()
    if ":" not in days:
        # returns by days
        first, end = list(map(int, days.split("-")))
        # first = (first - 1) * seconds_per_day
        # end = end * seconds_per_day
        if damping_factor is not None:
            workload_all = list(map(lambda l: int(l/damping_factor), workload_all))
        return workload_all[first: end]

    else:
        # return by full date
        start_date_str, end_date_str = days.split("-")
        start_date = parse_date_str(start_date_str)
        end_date = parse_date_str(end_date_str)
        start_index = (
            start_date - datetime.datetime(2023, 1, 1, 0, 0, 0)
        ).total_seconds()
        end_index = (end_date - datetime.datetime(2023, 1, 1, 0, 0, 0)).total_seconds()
        if damping_factor is not None:
            workload_all = list(map(lambda l: int(l/damping_factor), workload_all))
        return workload_all[int(start_index) : int(end_index) + 1]


# -*- coding: UTF-8 -*-
import json
import logging
import traceback

import logzero
import pike.discovery.py as discovery
from flask import Blueprint, Flask, Response, make_response, \
    jsonify
from flask.views import MethodView
from werkzeug.exceptions import HTTPException

_FORMAT = '%(color)s[%(levelname)s] %(message)s%(end_color)s'

LOG = logzero.setup_logger('demo.application',
                           level=logging.INFO,
                           formatter=logzero.LogFormatter(fmt=_FORMAT))

def _catch_all(error):
    if not isinstance(error, HTTPException):
        data = error.data if hasattr(error, 'data') else None
        tb = ''.join(traceback.format_tb(error.__traceback__))
        LOG.info('v' * 78)
        LOG.info(f'{error} {type(error)} \n{tb}'.strip())
        LOG.info('^' * 78)
        code = error.error_code if hasattr(error, 'error_code') else -1
        reason = error.message if hasattr(error, 'message') else str(error)
        retval = dict(msg=reason, data=data, code=code)
        retval['traceback'] = tb
        return Response(json.dumps(retval), 500)
    else:
        # LOG.info(error, exc_info=True)
        return error

def generate_bp(module):
    # 创建蓝图
    _bp = Blueprint('provider', __name__)
    num_routes = 0
    # 自动发现路由（具有 route 属性且值是 str 且具备响应请求的能力的类）
    for v in discovery.get_all_classes(module):
        if hasattr(v, 'route') and isinstance(v.route, str):
            LOG.info(f'Adding route {v.route} from {v.__name__} ...')
            # mapping
            _bp.add_url_rule(v.route, view_func=v.as_view(v.__name__))
            num_routes += 1
    LOG.info(f'#{num_routes} routes has been successfully added.')
    return _bp

def create_app(model):
    _app = Flask(__name__)
    # 创建并注册蓝图
    bp = generate_bp(model)
    _app.register_blueprint(bp)
    # 错误处理
    _app.register_error_handler(Exception, _catch_all)
    return _app

class BaseHandler(MethodView):

    @staticmethod
    def resp_format(code=0, msg='success', data=None):
        if type(data) == Response:
            return data
        return make_response(jsonify({
            'code': code,
            'msg': msg,
            'data': data
        }))


n=int(input())
d={}
temp=[]
for i in range(n):
    typ, word=input().split()
    temp.append(word)
    if word[:2] not in d:
        d[word[:2]]={word}
    else:
        d[word[:2]].add(word)
maxlen=0
for k,v in d.items():
    if len(v)>maxlen:
        maxlen=len(v)
        tw=k
        tempk=k[:2]
    elif len(v)==maxlen:
        if k[:2]<tempk:
            maxlen=len(v)
            tw=k
            tempk=k[:2]
print(tw)
print(maxlen)
for t in temp:
    for data in d[tw]:
        if data==t:
            print(data)


import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
import math
import SimpleITK as sitk

device = torch.device("cuda:0")
class NCC:
    """
    Local (over window) normalized cross correlation loss.
    """

    def __init__(self, win=None):
        self.win = win

    def loss(self, y_true, y_pred):

        I = y_true
        J = y_pred

        # get dimension of volume
        # assumes I, J are sized [batch_size, *vol_shape, nb_feats]
        ndims = len(list(I.size())) - 2
        assert ndims in [1, 2, 3], "volumes should be 1 to 3 dimensions. found: %d" % ndims

        # set window size
        win = [9] * ndims if self.win is None else self.win

        # compute filters
        sum_filt = torch.ones([1, 1, *win]).to(device)

        pad_no = math.floor(win[0]/2)

        if ndims == 1:
            stride = (1)
            padding = (pad_no)
        elif ndims == 2:
            stride = (1,1)
            padding = (pad_no, pad_no)
        else:
            stride = (1,1,1)
            padding = (pad_no, pad_no, pad_no)

        # get convolution function
        conv_fn = getattr(F, 'conv%dd' % ndims)

        # compute CC squares
        I2 = I * I
        J2 = J * J
        IJ = I * J

        I_sum = conv_fn(I, sum_filt, stride=stride, padding=padding)
        J_sum = conv_fn(J, sum_filt, stride=stride, padding=padding)
        I2_sum = conv_fn(I2, sum_filt, stride=stride, padding=padding)
        J2_sum = conv_fn(J2, sum_filt, stride=stride, padding=padding)
        IJ_sum = conv_fn(IJ, sum_filt, stride=stride, padding=padding)

        win_size = np.prod(win)
        u_I = I_sum / win_size
        u_J = J_sum / win_size

        cross = IJ_sum - u_J * I_sum - u_I * J_sum + u_I * u_J * win_size
        I_var = I2_sum - 2 * u_I * I_sum + u_I * u_I * win_size
        J_var = J2_sum - 2 * u_J * J_sum + u_J * u_J * win_size

        cc = cross * cross / (I_var * J_var + 1e-5)

        # cc_size = cc.shape
        # cc_sum = torch.sum(cc)
        # target_value = 0.99
        # target_sum = torch.sum(cc[cc>target_value])
        # target_size = cc[cc>target_value].shape
        # print(cc_size[0]*cc_size[1]*cc_size[2]*cc_size[3]*cc_size[4])
        # print(target_size[0])

        # mean = (cc_sum-target_sum)/(cc_size[0]*cc_size[1]*cc_size[2]*cc_size[3]*cc_size[4]-target_size[0])

        # print(cc_size)
        # return -mean

        #print(torch.sum(cc[cc>0.99]))

        return -torch.mean(cc)

class Grad:
    """
    N-D gradient loss.
    """

    def __init__(self, penalty='l1', loss_mult=None):
        self.penalty = penalty
        self.loss_mult = loss_mult

    def loss(self,  y_pred):
        # dy = torch.abs(y_pred[:, :, :, 1:, :, :] - y_pred[:, :, :, :-1, :, :])
        # dx = torch.abs(y_pred[:, :, :, :, 1:, :] - y_pred[:, :, :, :, :-1, :])
        # dz = torch.abs(y_pred[:, :, :, :, :, 1:] - y_pred[:, :, :, :, :, :-1])
        dt = torch.abs(y_pred[:, :, 1:, :, :, :] - y_pred[:, :, :-1, :, :, :])

        if self.penalty == 'l2':
            # dy = dy * dy
            # dx = dx * dx
            # dz = dz * dz
            dt = dt * dt

        # d = torch.mean(dx) + torch.mean(dy) + torch.mean(dz) + torch.mean(dt)
        # grad = d / 4.0
        d = torch.mean(dt)
        grad = d / 4.0

        if self.loss_mult is not None:
            grad *= self.loss_mult
        return grad

def cross_entropy_3D(input, target, weight=None, size_average=True):
    n, c, h, w, s = input.size()
    log_p = F.log_softmax(input, dim=1)
    log_p = log_p.transpose(1, 2).transpose(2, 3).transpose(3, 4).contiguous().view(-1, c)
    target = target.view(target.numel())
    loss = F.nll_loss(log_p, target, weight=weight, size_average=False)
    if size_average:
        loss /= float(target.numel())
    return loss

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

    def forward(self, logits, targets):
        class_num = logits.size(1)
        dice_sum = 0

        x = 0
        y = 0

        # inter = torch.sum(logits[:, 0, :, :, :] * targets[:, 0, :, :, :])
        # union = torch.sum(logits[:, 0, :, :, :]) + torch.sum(targets[:, 0, :, :, :])
        # dice = (2. * inter + 1) / (union + 1)
        # dice_sum += 0*dice
        # ###rv
        # inter = torch.sum(logits[:, 1, :, :, :] * targets[:, 1, :, :, :])
        # union = torch.sum(logits[:, 1, :, :, :]) + torch.sum(targets[:, 1, :, :, :])
        # dice = (2. * inter + 1) / (union + 1)
        # # print('1:',dice)
        #
        # # if dice > 0.97:
        # #     x = 0
        # # else:
        # #     x = 0.25
        # x = 0.3
        # dice_sum += x * dice
        # ##LV
        # inter = torch.sum(logits[:, 3, :, :, :] * targets[:, 3, :, :, :])
        # union = torch.sum(logits[:, 3, :, :, :]) + torch.sum(targets[:, 3, :, :, :])
        # dice = (2. * inter + 1) / (union + 1)
        # # print('3:', dice)
        # if dice > 0.97:
        #     y = 0
        # else:
        #     y = 0.25
        #
        # dice_sum += y * dice
        # ##myo
        # inter = torch.sum(logits[:, 2, :, :, :] * targets[:, 2, :, :, :])
        # union = torch.sum(logits[:, 2, :, :, :]) + torch.sum(targets[:, 2, :, :, :])
        # dice = (2. * inter + 1) / (union + 1)
        # # print('2:', dice)
        #
        # dice_sum += (1-x-y) * dice
        #
        # return 1-dice_sum

        for i in range(class_num):
            if i==0:
                inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
                union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
                dice = (2. * inter + 1) / (union + 1)
                dice_sum += dice*0.1
            elif i==1:
                inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
                union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
                dice = (2. * inter + 1) / (union + 1)
                dice_sum += dice * 0.35
            elif i == 2:
                inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
                union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
                dice = (2. * inter + 1) / (union + 1)
                dice_sum += dice * 0.35
            else:
                inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
                union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
                dice = (2. * inter + 1) / (union + 1)
                dice_sum += dice * 0.2

            # inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
            # union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
            # dice = (2. * inter + 1) / (union + 1)
            # dice_sum += dice
            # print(i,':',dice)
        # return 1 - dice_sum / class_num

        return 1 - dice_sum

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

    def forward(self, logits, targets):

        num_sum = torch.sum(targets, dim=(0, 2, 3, 4))
        w = torch.Tensor([0, 0, 0]).to(device)
        for i in range(targets.size(1)):
            if (num_sum[i] < 1):
                w[i] = 0
            else:
                w[i] = (0.1 * num_sum[i] + num_sum[i - 1] + num_sum[i - 2] + 1) / (torch.sum(num_sum) + 1)
        print(w)
        inter = w * torch.sum(targets * logits, dim=(0, 2, 3, 4))
        inter = torch.sum(inter)

        union = w * torch.sum(targets + logits, dim=(0, 2, 3, 4))
        union = torch.sum(union)

        return 1 - 2. * inter / union

def dice(logits, targets, class_index):
    inter = torch.sum(logits[:, class_index, :, :, :] * targets[:, class_index, :, :, :])
    union = torch.sum(logits[:, class_index, :, :, :]) + torch.sum(targets[:, class_index, :, :, :])
    dice = (2. * inter + 1) / (union + 1)
    return dice

from torch.autograd import Variable
import random
class ReplayBuffer:
    def __init__(self, max_size=50):
        assert max_size > 0, "Empty buffer or trying to create a black hole. Be careful."
        self.max_size = max_size
        self.data = []

    def push_and_pop(self, data):
        to_return = []
        for element in data.data:
            element = torch.unsqueeze(element, 0)
            if len(self.data) < self.max_size:
                self.data.append(element)
                to_return.append(element)
            else:
                if random.uniform(0, 1) > 0.5:
                    i = random.randint(0, self.max_size - 1)
                    to_return.append(self.data[i].clone())
                    self.data[i] = element
                else:
                    to_return.append(element)
        return Variable(torch.cat(to_return))

def location(seges,seged,bias,category):
    one = torch.ones_like(seges)
    zero = torch.zeros_like(seges)
    mi3=0
    mi4=0
    mx3=0
    mx4=0

    size = seges.shape

    if category ==4:
        seg_es1 = torch.unsqueeze(
            torch.unsqueeze(seges[0, 1, :, :, :] * 1 + seges[0, 2, :, :, :] * 2 + seges[0, 3, :, :, :] * 3, 0), 0)
        seg_es1 = seg_es1[:, :, :, :, :]
        one = torch.ones_like(seg_es1)
        zero = torch.zeros_like(seg_es1)

        seg_ed1 = torch.unsqueeze(
            torch.unsqueeze(seged[0, 1, :, :, :] * 1 + seged[0, 2, :, :, :] * 2 + seged[0, 3, :, :, :] * 3, 0), 0)

        seg_ed1 = seg_ed1[:, :, :, :, :]
    elif category ==2:
        seg_es1 = torch.unsqueeze(
            torch.unsqueeze(seges[0, 1, :, :, :] * 1 , 0), 0)
        seg_es1 = seg_es1[:, :, :, :, :]
        one = torch.ones_like(seg_es1)
        zero = torch.zeros_like(seg_es1)

        seg_ed1 = torch.unsqueeze(
            torch.unsqueeze(seged[0, 1, :, :, :] * 1 , 0), 0)

        seg_ed1 = seg_ed1[:, :, :, :, :]

    else:
        seg_es1 = torch.unsqueeze(
            torch.unsqueeze(seged[0, category, :, :, :] * category , 0), 0)

        seg_ed1 = torch.unsqueeze(
            torch.unsqueeze(seged[0, category, :, :, :] * category , 0), 0)

    seg_es1 = torch.where(seg_es1 >= 1, one, zero)
    seg_es1_0 = np.nonzero(seg_es1)
    seg_es_row3 = seg_es1_0[:, 3]
    mx_seg_es_row3 = torch.max(seg_es_row3)
    mi_seg_es_row3 = torch.min(seg_es_row3)
    seg_es_row4 = seg_es1_0[:, 4]
    mx_seg_es_row4 = torch.max(seg_es_row4)
    mi_seg_es_row4 = torch.min(seg_es_row4)

    seg_ed1 = torch.where(seg_ed1 >= 1, one, zero)
    seg_ed1_0 = np.nonzero(seg_ed1)
    seg_ed_row3 = seg_ed1_0[:, 3]
    mx_seg_ed_row3 = torch.max(seg_ed_row3)
    mi_seg_ed_row3 = torch.min(seg_ed_row3)
    seg_ed_row4 = seg_ed1_0[:, 4]
    mx_seg_ed_row4 = torch.max(seg_ed_row4)
    mi_seg_ed_row4 = torch.min(seg_ed_row4)

    if mi_seg_es_row3<mi_seg_ed_row3:
        mi3 = mi_seg_es_row3
    else:
        mi3 = mi_seg_ed_row3

    if mi_seg_es_row4<mi_seg_ed_row4:
        mi4 = mi_seg_es_row4
    else:
        mi4 = mi_seg_ed_row4

    if mx_seg_es_row3<mx_seg_ed_row3:
        mx3 = mx_seg_ed_row3
    else:
        mx3 = mx_seg_es_row3

    if mx_seg_es_row4<mx_seg_ed_row4:
        mx4 = mx_seg_ed_row4
    else:
        mx4 = mx_seg_es_row4

    mi3 = mi3-bias
    if mi3<0:
        mi3 = 0

    mi4 = mi4-bias
    if mi4<0:
        mi4 = 0

    if mx3+bias>size[3]:
        mx3 = size[3]
    else:
        mx3 = mx3+bias

    if mx4+bias>size[4]:
        mx4 = size[4]
    else:
        mx4 = mx4+bias

    return mi3,mx3,mi4,mx4

class crossentry(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, y_true, y_pred):
        smooth = 1e-6
        return -torch.mean(y_true * torch.log(y_pred+smooth))

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

    def forward(self, logits, targets):
        class_num = logits.size(1)
        dice_sum = 0

        x = 0
        y = 0

        for i in range(class_num):
            inter = torch.sum(logits[:, i, :, :, :] * targets[:, i, :, :, :])
            union = torch.sum(logits[:, i, :, :, :]) + torch.sum(targets[:, i, :, :, :])
            dice = (2. * inter + 1) / (union + 1)
            dice_sum += dice
            # print(i,':',dice)
        return 1-dice_sum / class_num

        # return 1 - dice_sum

class focal_loss(nn.Module):
    def __init__(self, alpha=0.25, gamma=2, num_classes=5, size_average=True):

        super(focal_loss, self).__init__()
        self.size_average = size_average
        if isinstance(alpha, (float, int)):    #仅仅设置第一类别的权重
            self.alpha = torch.zeros(num_classes)
            self.alpha[0] += alpha
            self.alpha[1:] += (1 - alpha)
        if isinstance(alpha, list):  #全部权重自己设置
            self.alpha = torch.Tensor(alpha)
        self.gamma = gamma

    def forward(self, inputs, targets):
        alpha = self.alpha
        # print('aaaaaaa',alpha)
        N = inputs.size(0)
        C = inputs.size(1)
        P = F.softmax(inputs,dim=1)
       # / print('ppppppppppppppppppppp', P)
        # ---------one hot start--------------#
        class_mask = inputs.data.new(N, C).fill_(0)  # 生成和input一样shape的tensor
        # print('依照input shape制作:class_mask\n', class_mask)
        class_mask = class_mask.requires_grad_()  # 需要更新， 所以加入梯度计算
        ids = targets.view(-1, 1)  # 取得目标的索引
        # print('取得targets的索引\n', ids)
        class_mask.data.scatter_(1, ids.data, 1.)  # 利用scatter将索引丢给mask
        # print('targets的one_hot形式\n', class_mask)  # one-hot target生成
        # ---------one hot end-------------------#
        probs = (P * class_mask).sum(1).view(-1, 1)
        # print('留下targets的概率（1的部分），0的部分消除\n', probs)
        # 将softmax * one_hot 格式，0的部分被消除 留下1的概率， shape = (5, 1), 5就是每个target的概率

        log_p = probs.log()
        # print('取得对数\n', log_p)
        # 取得对数
        loss = torch.pow((1 - probs), self.gamma) * log_p
        batch_loss = -alpha *loss.t()  # 對應下面公式
        # print('每一个batch的loss\n', batch_loss)
        # batch_loss就是取每一个batch的loss值

        # 最终将每一个batch的loss加总后平均
        if self.size_average:
            loss = batch_loss.mean()
        else:
            loss = batch_loss.sum()
        # print('loss值为\n', loss)
        return loss


import random

def main():
    print("Welcome to Rock-Paper-Scissors Game\n")
    print("1.Rock 2.Paper 3.Scissors")
    score=0
    comp_score=0
    while(True):
        comp_choice=random.randint(1,3)
        try:
            user_choice=int(input("Enter Your choice(only 1,2,3):"))
        except:
            print("Invalid Input.Try Again.")
            continue
        if score==3:
            print("Congratulations. You have won the game.")
            break
        if comp_score==3:
            print(" You Lost the game.Better luck next time")
            break
        result=check_winner(comp_choice,user_choice)
        if result==0:
            print("Tie!")
        elif result==1:
            score+=1
            print("You won this round")
        else:
            comp_score+=1
            print("You lost This round")

def check_winner(comp,user):
    if comp==user:
        return 0

    if (user==1 and comp==3) or (user==2 and comp==1) or (user==3 and comp==2):
        return 1
    else:
        return -1

if __name__=="__main__":
    main()


"""matplotlib
plotでの軸の範囲の指定方法(axis)
x軸、y軸の値の比率を揃える場合: equalオプション

[説明ページ]
https://tech.nkhn37.net/matplotlib-plot-lim-axis/#xy_equal
"""
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('seaborn-whitegrid')

x = np.linspace(0, 10, 100)

# グラフ表示
plt.plot(x, np.sin(x))
# equalで軸の比率をそろえる
plt.axis('equal')

plt.show()


#Problem 3

import time

balance = 987654321
annualInterestRate = 0.2

b=balance
aiR=annualInterestRate
t=0
j=1
low=balance/12.
high=balance*((1+annualInterestRate/12)**12)/12
def bal(x):
    p=x
    b=balance
    t=0
    for i in range(12):
        b=(b-p)*(1+aiR/12)
        t=t+p
    return b
#print(bal(451.63))

while abs(round(b,2))>0.01:
    fp=(low+high)/2.
    bl=bal(low)
    bh=bal(high)
    b=bal(fp)

    if b<0:
        high=fp

    else:

        if(b>bl and b>0):
            high=fp
        else:
            low=fp
#    print('I entered '+str(j)+' times.')
    j=j+1

print('Lowest Payment: '+str(round(fp,2)))
print('Time: ' + str(time.clock()))


def reverseSort(a):
    cost = 0
    for i in range(len(a)-1):

        # find minimum element from i to end
        m = min(a[i:])

        # find index of the minimum element
        m_index = a[i:].index(m)

        # reverse from i to m_index
        a[i:m_index+i+1] = a[i:m_index+i+1][::-1]

        # keep track of cost
        cost += len(a[i:m_index+i+1])

    # print(*a)
    return cost

for _ in range(int(input())):

    n = int(input())
    a = list(map(int, input().split()))

    print('Case #', _+1, ': ', reverseSort(a), sep='')


import tkinter as tk

window1=tk.Tk()

window1.title("My Window!")
window1.geometry('500x300')
#设置主窗口
#==========================
ety1=tk.Entry(window1,show=None)
ety1.pack()

def insert_point(): #在指针处插入
    var=ety1.get()
    t.insert('insert',var)

def insert_end():   #在文本框后面插入
    var=ety1.get()
    t.insert('end',var)

btn1=tk.Button(window1,text='insert point',width=10,height=2,command=insert_point)
btn1.pack()

btn2=tk.Button(window1,text='insert end',width=10,height=2,command=insert_end)
btn2.pack()

t=tk.Text(window1,height=3)
t.pack()

#==========================
#主窗口循环显示
window1.mainloop()