import logging

from mysql_client.client import DatabaseHandle

class AppointmentDao:
    """
    A class for retrieving appointments from the database.

    Attributes:
        __mysql_client (DatabaseHandle): An instance of the `DatabaseHandle` class.

    """

    def __init__(self):
        """
        Initializes the `AppointmentDao` class and creates an instance of the `DatabaseHandle` class.
        """
        self.__mysql_client = DatabaseHandle()

    def __make_update_stmt(self):
        """
        Creates the SQL update statement for updating appointments.

        Returns:
            str: The SQL update statement.
        """
        SQL_UPDATE_STMNT = "UPDATE APPOINTMENT SET STATUS = 'RESOLVED' WHERE FIRST_NAME = %s AND LAST_NAME = %s AND PHONE_NUMBER = %s;"

        return SQL_UPDATE_STMNT

    def __make_select_stmt(self):
        """
        Creates the SQL select statement for retrieving the updated appointment.

        Returns:
            str: The SQL select statement.
        """
        SQL_SELECT_STMNT = "SELECT ID,FIRST_NAME,LAST_NAME FROM APPOINTMENT WHERE FIRST_NAME = %s AND LAST_NAME = %s AND PHONE_NUMBER = %s;"

        return SQL_SELECT_STMNT

    def update_status(self, data) -> dict:
        """
        Retrieves the next appointment from the APPOINTMENT table and updates its status to "RESOLVED".

        Returns:
            dict: A list of dictionaries, where each dictionary represents a customer appointment.

        Raises:
            Exception: If an error occurs while updating customer status.
        """
        connection = self.__mysql_client.client()
        update_cursor = connection.cursor()

        SQL_UPDATE_STMNT = self.__make_update_stmt()

        logging.debug(SQL_UPDATE_STMNT)

        try:
            logging.debug("Started updating customer status")
            params = (data["fname"], data["lname"], data["phone_number"])
            update_cursor.execute(SQL_UPDATE_STMNT, params)
            connection.commit()
            self.__mysql_client.close()
        except Exception as e:
            logging.error("Unable to update customer status", str(e))
            raise e

    def retrieve_status_id(self, data) -> dict:
        """
        Retrieves the next appointment from the APPOINTMENT table and updates its status to "RESOLVED".

        Returns:
            dict: A list of dictionaries, where each dictionary represents a customer appointment.

        Raises:
            Exception: If an error occurs while updating customer status.
        """
        select_connection = self.__mysql_client.client()
        select_cursor = select_connection.cursor(dictionary=True)
        SQL_SELECT_STMNT = self.__make_select_stmt()
        logging.debug(SQL_SELECT_STMNT)

        try:
            logging.debug("Started updating customer status")
            params = (data["fname"], data["lname"], data["phone_number"])
            select_cursor.execute(SQL_SELECT_STMNT, params)
            result = select_cursor.fetchall()[-1]
            select_connection.commit()
            self.__mysql_client.close()
            return result or None
        except Exception as e:
            logging.error("Unable to select customer status", str(e))
            raise e


import yaml
import argparse
import torch
import pandas as pd
import os
import numpy as np
from tqdm import tqdm
from sklearn.metrics import f1_score, precision_score, recall_score
from transformers import (
    AutoTokenizer,
    AutoModelForSequenceClassification,
)

with open("./config.yaml") as f:
    threshold_dict = yaml.load(f, Loader=yaml.FullLoader)
    threshold_dict = threshold_dict["threshold"]

def _get_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_name", type=str, default="tunib/electra-ko-base")
    parser.add_argument("--dir_path", type=str, default="/home/ckpt")
    parser.add_argument("--file_path", type=str, default="")
    parser.add_argument("--gpus", type=list, default=[0])
    parser.add_argument("--num_labels", type=int, default=7)
    parser.add_argument("--data_path", type=str, default="./data/test.csv")
    return parser

parser = _get_parser()
args = parser.parse_args()

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
tokenizer = AutoTokenizer.from_pretrained(args.model_name)
model = AutoModelForSequenceClassification.from_pretrained(
    args.model_name, num_labels=args.num_labels
)

trained_model_dict = torch.load(f"{args.dir_path}/{args.file_path}")["state_dict"]

model_dict = dict()

for key in trained_model_dict:
    model_dict[key[6:]] = trained_model_dict[key]

model.load_state_dict(model_dict)
model.to(device)
model.eval()

df = pd.read_csv(args.data_path, encoding="utf-8", index_col=0)
os.environ["TOKENIZERS_PARALLELISM"] = "false"
comments = df["comment"]
comments = list(comments)
cols = threshold_dict.keys()
diction = {}

for col in cols:
    diction[col] = []
    diction[f"{col}_label"] = []

for idx, my_input in tqdm(enumerate(comments)):
    tokenized = tokenizer(
        my_input,
        return_tensors="pt",
        max_length=512,
        padding="max_length",
        truncation=True,
    ).to(device)
    output = model(**tokenized)

    logits = np.array(output.logits.cpu().detach()).squeeze()
    label = df.loc[idx][: args.num_labels].tolist()
    label = np.array(label)

    for i, col in enumerate(cols):
        diction[col].append(0 if threshold_dict[col] > logits[i] else 1)
        diction[f"{col}_label"].append(label[i])

f1_scores = []
precisions = []
recalls = []

for col in cols:
    f1 = f1_score(diction[col], diction[f"{col}_label"])
    prec = precision_score(diction[col], diction[f"{col}_label"])
    rec = recall_score(diction[col], diction[f"{col}_label"])
    f1_scores.append(f1)
    precisions.append(prec)
    recalls.append(rec)
    print(f"{col} f1: {f1}")
    print(f"{col} precision: {prec}")
    print(f"{col} recall: {rec}")

print(f"macro f1 score : {sum(f1_scores) / len(f1_scores)}")
print(f"macro precision score : {sum(precisions) / len(precisions)}")
print(f"macro recall score : {sum(recalls) / len(recalls)}")


# game options/settings

TITLE = "Skybound"
WIDTH = 480
HEIGHT = 600
FPS = 60
FONT_NAME = 'Times New Roman'
HS_FILE = "highscore.txt"
SPRITESHEET = "spritesheet_jumper.png"

# World properties

GRAVITY = 0.75
BOOST_POWER = 60
POW_SPAWN_PCT = 7
MOB_FREQ = 5000
PLAYER_LAYER = 2
MOB_LAYER = 2
POW_LAYER = 1
PLATFORM_LAYER = 1
CLOUD_LAYER = 0

# Player properties
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
JUMP_ACC = -20

# Starting platforms
PLATFORM_LIST = [(0, HEIGHT - 60),
                 (WIDTH / 2 - 50, HEIGHT * 3 / 4,),
                 (WIDTH / 2 - 50, HEIGHT / 2),
                 (WIDTH / 2 - 50, HEIGHT / 4)]

# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
SKY_BLUE = (30, 144, 255)
GOLD = (212, 175, 55)


from flask import Blueprint, abort, url_for
from db import database

app = Blueprint('api_device', __name__)

@app.route('/device/<int:id>')
def device_details(id: int):
    """
        Device details
        ---
        description: Device details
        summary: Get device by id
        tags:
          - device
        responses:
          '200':
            description: Device details
          '404':
            description: Device not found
        parameters:
          - name: id
            in: path
            description: id of the device
            required: true
    """

    _, cur = database()
    sql = """
        SELECT
            -- base
                D.name, D.room,
            -- light
                DL.status,
            -- windows
                DW.status,
            -- alarm
                DA.status,
            -- thermostat
                DT.temperature, DT.umidity
        FROM `device` D
        LEFT JOIN `device_light` DL ON DL.device = D.id
        LEFT JOIN `device_window` DW ON DW.device = D.id
        LEFT JOIN `device_alarm` DA ON DA.device = D.id
        LEFT JOIN `device_thermostat` DT ON DT.device = D.id
        WHERE D.id = %s
    """
    cur.execute(sql, [id])

    if cur.rowcount == 0:
        abort(400)

    result = {}
    for key, value in cur.fetchone().items():
        if key == 'room':
            result[key] = url_for('api_home.room_details', id=value, _external=True)
        elif value != None and 'status' in key:
            result[key[3:]] = value
        elif value != None:
            result[key] = value

    return result


"""
Source:
https://stackoverflow.com/questions/37517936/matplotlib-scatterplot-open-image-corresponding-to-point-which-i-click
"""
import matplotlib.image as mpimg
import numpy as np
import matplotlib.pyplot as plt

plt.close('all')

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'o')

def onclick(event):
    ix, iy = event.xdata, event.ydata
    print("I clicked at x={0:5.2f}, y={1:5.2f}".format(ix, iy))

    # Calculate, based on the axis extent, a reasonable distance
    # from the actual point in which the click has to occur (in this case 5%)
    ax = plt.gca()
    dx = 0.05 * (ax.get_xlim()[1] - ax.get_xlim()[0])
    dy = 0.05 * (ax.get_ylim()[1] - ax.get_ylim()[0])

    # Check for every point if the click was close enough:
    for i in range(len(x)):
        if (x[i] > ix - dx and x[i] < ix + dx and y[i] > iy - dy and y[i] < iy + dy):
            print("You clicked close enough!")

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()


from plone.app.testing import PloneSandboxLayer
from plone.app.testing import applyProfile
from plone.app.testing import PLONE_FIXTURE
from plone.app.testing import IntegrationTesting
from plone.app.testing import FunctionalTesting

from plone.testing import z2

from zope.configuration import xmlconfig

class CmsgardenpolicyLayer(PloneSandboxLayer):

    defaultBases = (PLONE_FIXTURE,)

    def setUpZope(self, app, configurationContext):
        # Load ZCML
        import cmsgarden.policy
        xmlconfig.file(
            'configure.zcml',
            cmsgarden.policy,
            context=configurationContext
        )

        # Install products that use an old-style initialize() function
        #z2.installProduct(app, 'Products.PloneFormGen')

#    def tearDownZope(self, app):
#        # Uninstall products installed above
#        z2.uninstallProduct(app, 'Products.PloneFormGen')

    def setUpPloneSite(self, portal):
        applyProfile(portal, 'cmsgarden.policy:default')

CMSGARDEN_POLICY_FIXTURE = CmsgardenpolicyLayer()
CMSGARDEN_POLICY_INTEGRATION_TESTING = IntegrationTesting(
    bases=(CMSGARDEN_POLICY_FIXTURE,),
    name="CmsgardenpolicyLayer:Integration"
)
CMSGARDEN_POLICY_FUNCTIONAL_TESTING = FunctionalTesting(
    bases=(CMSGARDEN_POLICY_FIXTURE, z2.ZSERVER_FIXTURE),
    name="CmsgardenpolicyLayer:Functional"
)


import csv
from bs4 import BeautifulSoup
from tqdm import tqdm
from request import request
from scrape_book import scrape_book
from scrape_category import scrape_category
from write_file import save_book

BASE_DIR = "http://books.toscrape.com/"

def scrape_all_book_category(url_scrape):
    category_list = scrape_category(url_scrape)
    for link in category_list:
        dictionnary_book = scrape_book(link)
        save_book(dictionnary_book)

def scrape(url):
    html = request(url)
    soup = BeautifulSoup(html, "html.parser")
    all_category_list = []
    lis = soup.find("ul", {"class": "nav nav-list"}).find("ul").findAll("li")
    for li in lis:
        link = BASE_DIR + li.find("a")["href"]
        all_category_list.append(link)
    for link in tqdm(all_category_list):
        scrape_all_book_category(link)

scrape(BASE_DIR)


# -*- coding: utf-8 -*-
"""Python packaging."""
from os.path import abspath, dirname, join
from setuptools import setup

def read_relative_file(filename):
    """Returns contents of the given file, which path is supposed relative
    to this module."""
    with open(join(dirname(abspath(__file__)), filename)) as f:
        return f.read()

def packages(project_name):
    """Return list of packages distributed by project based on its name.

    >>> packages('foo')
    ['foo']
    >>> packages('foo.bar')
    ['foo', 'foo.bar']
    >>> packages('foo.bar.baz')
    ['foo', 'foo.bar', 'foo.bar.baz']
    >>> packages('FooBar')
    ['foobar']

    Implements "Use a single name" convention described in :pep:`423`.

    """
    name = str(project_name).lower()
    if '.' in name:  # Using namespace packages.
        parts = name.split('.')
        return ['.'.join(parts[0:i]) for i in range(1, len(parts) + 1)]
    else:  # One root package or module.
        return [name]

def namespace_packages(project_name):
    """Return list of namespace packages distributed in this project, based on
    project name.

    >>> namespace_packages('foo')
    []
    >>> namespace_packages('foo.bar')
    ['foo']
    >>> namespace_packages('foo.bar.baz')
    ['foo', 'foo.bar']
    >>> namespace_packages('Foo.BaR.BAZ') == namespace_packages('foo.bar.baz')
    True

    Implements "Use a single name" convention described in :pep:`423`.

    """
    package_list = packages(project_name)
    package_list.pop()  # Ignore last element.
    # Remaining packages are supposed to be namespace packages.
    return package_list

NAME = 'pussycache'
version = read_relative_file('VERSION').strip()
readme = read_relative_file('README.md')
requirements = []

dependency_links = []

entry_points = {
}

if __name__ == '__main__':  # ``import setup`` doesn't trigger setup().
    setup(name=NAME,
          version=version,
          description="""Cache Backend system for python objects""",
          long_description=readme,
          classifiers=['Development Status :: 4 - Beta',
                       'License :: OSI Approved :: BSD License',
                       'Programming Language :: Python :: 2.7',
                       'Programming Language :: Python :: 2.6',
                       'Framework :: Django',
                       ],
          keywords='cache',
          author='Novapost Team',
          author_email='peopleask@novapost.fr',
          url='https://github.com/novapost/%s' % NAME,
          license='BSD',
          packages=packages(NAME),
          namespace_packages=namespace_packages(NAME),
          include_package_data=True,
          zip_safe=False,
          install_requires=requirements,
          dependency_links=dependency_links,
          entry_points=entry_points,
          test_suite='nose.collector',
          setup_requires=['nose'],
          tests_require=['redis', 'django'])


# main program
def main():

    # user input
    st = input("Text: ")

    # counters
    wol = len(st)
    letter = 0
    word = 0
    sentence = 0
    key = True

    # char checker
    for i in range(wol):

        if (ord(st[i]) >= 65 and ord(st[i]) <= 90) or (ord(st[i]) >= 97 and ord(st[i]) <= 122):
            letter += 1

        if ord(st[i]) == 32:
            key = True

        else:
            if key == True and ((ord(st[i]) >= 65 and ord(st[i]) <= 90) or (ord(st[i]) >= 97 and ord(st[i]) <= 122)):
                word += 1
                key =False

        if (ord(st[i]) == 63) or (ord(st[i]) == 46) or (ord(st[i]) == 33):
            sentence += 1

    sum_of = ReadAbility_test(letter, sentence, word)

    if sum_of < 1:
        print("Before Grade 1")
    elif sum_of > 16:
        print("Grade 16+")
    else:
        print(f"Grade {round(sum_of)}")

# calculate the score
def ReadAbility_test(L, S, W):

    avg_l = float((L / W) * 100)
    avg_s = float((S / W) * 100)
    total = ((0.0588 * avg_l) - (0.296 * avg_s) - 15.8)
    return total

if __name__ == "__main__":
    main()


import os
from shutil import rmtree
from unittest.mock import mock_open
from unittest.mock import patch

import boto3
import cfn_flip.yaml_dumper
import pytest
import yaml
from cfn_tools import load_yaml
from click.testing import CliRunner
from moto import mock_cloudformation
from moto import mock_ec2
from moto import mock_ecs
from moto import mock_elbv2
from moto import mock_sts
from moto import mock_wafv2

from dbt_copilot_helper.commands.waf import attach_waf
from dbt_copilot_helper.commands.waf import check_waf
from dbt_copilot_helper.commands.waf import custom_waf
from tests.copilot_helper.conftest import TEST_APP_DIR

@pytest.fixture
def setup_test_directory():
    copilot_dir = TEST_APP_DIR / "copilot"
    if copilot_dir.exists():
        rmtree(copilot_dir)
    os.mkdir(copilot_dir)
    os.chdir(TEST_APP_DIR)
    yield
    if copilot_dir.exists():
        rmtree(copilot_dir)

@mock_wafv2
def test_check_waf():
    session = boto3.Session()
    arn = session.client("wafv2").create_web_acl(
        Name="default",
        Scope="REGIONAL",
        DefaultAction={},
        VisibilityConfig={
            "SampledRequestsEnabled": True,
            "CloudWatchMetricsEnabled": True,
            "MetricName": "blah",
        },
    )["Summary"]["ARN"]

    assert check_waf(session) == arn

@mock_wafv2
def test_check_waf_no_arn():
    session = boto3.Session()
    session.client("wafv2").create_web_acl(
        Name="non-default",
        Scope="REGIONAL",
        DefaultAction={},
        VisibilityConfig={
            "SampledRequestsEnabled": True,
            "CloudWatchMetricsEnabled": True,
            "MetricName": "blah",
        },
    )["Summary"]["ARN"]

    assert check_waf(session) == ""

@mock_sts
@mock_wafv2
def test_attach_waf_no_default(alias_session):
    boto3.Session().client("wafv2").create_web_acl(
        Name="non-default",
        Scope="REGIONAL",
        DefaultAction={},
        VisibilityConfig={
            "SampledRequestsEnabled": True,
            "CloudWatchMetricsEnabled": True,
            "MetricName": "blah",
        },
    )["Summary"]["ARN"]
    runner = CliRunner()
    result = runner.invoke(
        attach_waf, ["--app", "app", "--project-profile", "foo", "--svc", "svc", "--env", "env"]
    )

    assert "Default WAF rule does not exists in this AWS account," in result.output

@mock_ec2
@mock_ecs
@mock_elbv2
@mock_sts
@mock_wafv2
def test_attach_waf(alias_session):
    session = boto3.Session()
    vpc_id = session.client("ec2").create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]["VpcId"]
    subnet_id = session.client("ec2").create_subnet(VpcId=vpc_id, CidrBlock="10.0.0.0/16")[
        "Subnet"
    ]["SubnetId"]
    elbv2_client = session.client("elbv2")
    lb_response = elbv2_client.create_load_balancer(Name="foo", Subnets=[subnet_id])
    dns_name = lb_response["LoadBalancers"][0]["DNSName"]
    lb_arn = lb_response["LoadBalancers"][0]["LoadBalancerArn"]
    target_group = elbv2_client.create_target_group(
        Name="foo", Protocol="HTTPS", Port=80, VpcId=vpc_id
    )
    target_group_arn = target_group["TargetGroups"][0]["TargetGroupArn"]
    elbv2_client.create_listener(
        LoadBalancerArn=lb_arn,
        DefaultActions=[{"Type": "forward", "TargetGroupArn": target_group_arn}],
    )
    ecs_client = session.client("ecs")
    ecs_client.create_cluster(clusterName="app-env-svc")
    ecs_client.create_service(
        cluster="app-env-svc",
        serviceName="app-env-svc",
        loadBalancers=[{"loadBalancerName": "foo", "targetGroupArn": target_group_arn}],
    )
    open_mock = mock_open(read_data='{"environments": {"env": {"http": {"alias": "blah"}}}}')
    acl_arn = session.client("wafv2").create_web_acl(
        Name="default",
        Scope="REGIONAL",
        DefaultAction={},
        VisibilityConfig={
            "SampledRequestsEnabled": True,
            "CloudWatchMetricsEnabled": True,
            "MetricName": "blah",
        },
    )["Summary"]["ARN"]
    runner = CliRunner()
    response = session.client("wafv2").get_web_acl_for_resource(ResourceArn=lb_arn)

    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
    with patch("dbt_copilot_helper.commands.dns.open", open_mock):
        result = runner.invoke(
            attach_waf, ["--app", "app", "--project-profile", "foo", "--svc", "svc", "--env", "env"]
        )

    assert f"Default WAF is now associated with {dns_name} for domain blah" in result.output

    response = session.client("wafv2").get_web_acl_for_resource(ResourceArn=lb_arn)

    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200

    # We should have more assertions here, but currently moto only supports associating apigateway stages, so it's not possible to retrieve that info.
    # https://github.com/getmoto/moto/blob/master/moto/wafv2/models.py#L94C10-L94C10

@mock_sts
def test_custom_waf_file_not_found(alias_session, setup_test_directory):
    runner = CliRunner()
    result = runner.invoke(
        custom_waf,
        [
            "--app",
            "app",
            "--project-profile",
            "foo",
            "--svc",
            "svc",
            "--env",
            "env",
            "--waf-path",
            "not-a-path",
        ],
    )
    path_string = f"{TEST_APP_DIR}/not-a-path"

    assert f"File failed lint check.\n{path_string}" in result.output
    assert result.exit_code == 0

@mock_cloudformation
@mock_sts
def test_custom_waf_invalid_yml(alias_session, setup_test_directory):
    runner = CliRunner()
    result = runner.invoke(
        custom_waf,
        [
            "--app",
            "app",
            "--project-profile",
            "foo",
            "--svc",
            "svc",
            "--env",
            "env",
            "--waf-path",
            "copilot/environments/addons/invalid_cloudformation_template.yml",
        ],
    )
    path_string = str(
        TEST_APP_DIR / "copilot" / "environments" / "addons" / "invalid_cloudformation_template.yml"
    )

    assert result.exit_code == 0
    assert f"File failed lint check.\n{path_string}" in result.output

# No Moto CloudFormation support for AWS::WAFv2::WebACL
@mock_cloudformation
@mock_sts
@patch("dbt_copilot_helper.commands.waf.check_aws_conn")
@patch("dbt_copilot_helper.commands.waf.create_stack")
def test_custom_waf_cf_stack_already_exists(
    create_stack, check_aws_conn, alias_session, setup_test_directory
):
    check_aws_conn.return_value = alias_session
    create_stack.side_effect = alias_session.client(
        "cloudformation"
    ).exceptions.AlreadyExistsException({"Error": {"Code": 666, "Message": ""}}, "operation name")
    runner = CliRunner()
    result = runner.invoke(
        custom_waf,
        [
            "--app",
            "app",
            "--project-profile",
            "foo",
            "--svc",
            "svc",
            "--env",
            "env",
            "--waf-path",
            "waf.yml",
        ],
    )

    assert "CloudFormation Stack already exists" in result.output
    assert result.exit_code == 0

@mock_cloudformation
@mock_sts
@patch(
    "dbt_copilot_helper.commands.waf.botocore.client.BaseClient._make_api_call",
    return_value={"Stacks": [{"StackStatus": "DELETE_IN_PROGRESS"}]},
)
@patch(
    "dbt_copilot_helper.commands.waf.create_stack",
    return_value={"StackId": "abc", "ResponseMetadata": {"HTTPStatusCode": 200}},
)
@patch("dbt_copilot_helper.commands.waf.check_aws_conn")
def test_custom_waf_delete_in_progress(
    check_aws_conn, create_stack, describe_stacks, alias_session, setup_test_directory
):
    check_aws_conn.return_value = alias_session
    runner = CliRunner()
    result = runner.invoke(
        custom_waf,
        [
            "--app",
            "app",
            "--project-profile",
            "foo",
            "--svc",
            "svc",
            "--env",
            "env",
            "--waf-path",
            "waf.yml",
        ],
    )

    describe_stacks.assert_called_once_with("DescribeStacks", {"StackName": "abc"})
    assert "Failed to create CloudFormation stack, see AWS webconsole for details" in result.output
    assert result.exit_code == 0

@mock_cloudformation
@mock_ec2
@mock_elbv2
@mock_sts
@mock_wafv2
@patch("dbt_copilot_helper.commands.waf.get_load_balancer_domain_and_configuration")
@patch(
    "dbt_copilot_helper.commands.waf.create_stack",
    return_value={"StackId": "abc", "ResponseMetadata": {"HTTPStatusCode": 200}},
)
@patch("dbt_copilot_helper.commands.waf.check_aws_conn")
def test_custom_waf(
    check_aws_conn,
    create_stack,
    get_elastic_load_balancer_domain_and_configuration,
    alias_session,
    setup_test_directory,
):
    cf_client = alias_session.client("cloudformation")

    # We need to ensure a specific instance of the cloudformation client is returned by custom_waf, in order to assert that create_stack is called with this client
    def client(*args, **kwargs):
        if args and args[0] == "cloudformation":
            return cf_client
        else:
            service_name = args[0]
            return boto3.Session().client(service_name)

    alias_session.client = client
    check_aws_conn.return_value = alias_session
    vpc_id = alias_session.client("ec2").create_vpc(CidrBlock="10.0.0.0/16")["Vpc"]["VpcId"]
    subnet_id = alias_session.client("ec2").create_subnet(VpcId=vpc_id, CidrBlock="10.0.0.0/16")[
        "Subnet"
    ]["SubnetId"]
    elbv2_client = alias_session.client("elbv2")
    lb_arn = elbv2_client.create_load_balancer(Name="foo", Subnets=[subnet_id])["LoadBalancers"][0][
        "LoadBalancerArn"
    ]
    load_balancer_configuration = elbv2_client.describe_load_balancers(LoadBalancerArns=[lb_arn])[
        "LoadBalancers"
    ][0]
    get_elastic_load_balancer_domain_and_configuration.return_value = (
        "domain-name",
        load_balancer_configuration,
    )
    dns_name = load_balancer_configuration["DNSName"]
    runner = CliRunner()

    # patching here, to avoid inadvertently mocking the moto test setup calls above, expecting two different boto methods to be called
    with patch(
        "dbt_copilot_helper.commands.waf.botocore.client.BaseClient._make_api_call",
        side_effect=[
            {
                "Stacks": [
                    {
                        "StackStatus": "CREATE_COMPLETE",
                        "Outputs": [{"OutputValue": "somekinda-waf:arn"}],
                    }
                ]
            },
            {"ResponseMetadata": {"HTTPStatusCode": 200}},
        ],
    ) as api_call:
        result = runner.invoke(
            custom_waf,
            [
                "--app",
                "app",
                "--project-profile",
                "foo",
                "--svc",
                "svc",
                "--env",
                "env",
                "--waf-path",
                "waf.yml",
            ],
        )

    assert f"WAF created: somekinda-waf:arn" in result.output
    api_call.assert_any_call("DescribeStacks", {"StackName": "abc"})
    api_call.assert_called_with(
        "AssociateWebACL", {"WebACLArn": "somekinda-waf:arn", "ResourceArn": lb_arn}
    )
    assert f"Custom WAF is now associated with {dns_name}" in result.output
    assert result.exit_code == 0

    with open("waf.yml", "r") as fd:
        data_dict = load_yaml(fd)
        dumper = cfn_flip.yaml_dumper.get_dumper(clean_up=True, long_form=False)
        raw = yaml.dump(data_dict, Dumper=dumper, default_flow_style=False, allow_unicode=True)

    create_stack.assert_called_once_with(cf_client, "app", "svc", "env", raw)


import pandas as pd
import numpy as np
from sklearn.model_selection import KFold
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Dropout, Embedding, Conv1D, GlobalMaxPooling1D
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, hamming_loss

# 读取CSV数据
df = pd.read_csv('Sample_result_feature.csv', header=None)

# 提取特征和标签
X = df.iloc[:, 1:5].values
y = df.iloc[:, -1].values

# 将标签转换为one-hot编码
num_classes = len(np.unique(y))
y = np.eye(num_classes)[y]

# 将文本数据转换为数值序列
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(X[:, 0])
X = tokenizer.texts_to_sequences(X[:, 0])
X = pad_sequences(X, maxlen=50)

# 定义十折交叉验证
kfold = KFold(n_splits=10, shuffle=False)
# kfold = KFold(n_splits=10, shuffle=True, random_state=42)

# 定义指标列表
acc_list = []
precision_list = []
recall_list = []
f1_score_list = []
hamming_losses=[]

# 循环进行十折交叉验证
for train_idx, test_idx in kfold.split(X, y):
    # 划分训练集和测试集
    X_train, y_train = X[train_idx], y[train_idx]
    X_test, y_test = X[test_idx], y[test_idx]

    # 构建CNN模型
    model = Sequential()
    model.add(Embedding(5000, 32, input_length=50))
    model.add(Conv1D(64, 5, activation='relu'))
    model.add(GlobalMaxPooling1D())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    # 编译和训练模型
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    model.fit(X_train, y_train, epochs=10, batch_size=32)

    # 预测测试集
    y_pred = model.predict(X_test)
    y_pred = np.argmax(y_pred, axis=1)
    y_test = np.argmax(y_test, axis=1)

    # 计算指标
    acc = accuracy_score(y_test, y_pred)
    precision = precision_score(y_test, y_pred, average='macro')
    recall = recall_score(y_test, y_pred, average='macro')
    f1 = f1_score(y_test, y_pred, average='macro')
    hamming=hamming_loss(y_test, y_pred)
    # 将指标加入列表
    acc_list.append(acc)
    precision_list.append(precision)
    recall_list.append(recall)
    f1_score_list.append(f1)
    hamming_losses.append(hamming_loss(y_test, y_pred))

    # 输出指标
    print(f"accuracy: {acc:.4f}, precision: {precision:.4f}, recall: {recall:.4f}, f1-score: {f1:.4f}, hamming:{hamming:.4f}")

# 输出十折交叉验证结果的平均指标
print("Average of accuracy: {:.4f}".format(np.mean(acc_list)))
print("Average of precision: {:.4f}".format(np.mean(precision_list)))
print("Average of recall: {:.4f}".format(np.mean(recall_list)))
print("Average of f1-score: {:.4f}".format(np.mean(f1_score_list)))
print("Average of hamming: {:.4f}".format(np.mean(hamming_losses)))

with open('result_cnn_without_feature.txt','w',encoding='utf-8')as f:
    for i in range(len(acc_list)):
        f.write(f'Fold {i+1} Accuracy: {acc_list[i]:.4f}'+'\n')
        f.write(f'Fold {i+1} Precision: {precision_list[i]:.4f}'+'\n')
        f.write(f'Fold {i+1} Recall: {recall_list[i]:.4f}'+'\n')
        f.write(f'Fold {i+1} F1-score: {f1_score_list[i]:.4f}'+'\n')
        f.write(f'Fold {i+1} Hamming Loss: {hamming_losses[i]:.4f}'+'\n')
    f.write(f'Average Accuracy: {sum(acc_list) / len(acc_list):.4f}'+'\n')
    f.write(f'Average Precision: {sum(precision_list) / len(precision_list):.4f}'+'\n')
    f.write(f'Average Recall: {sum(recall_list) / len(recall_list):.4f}'+'\n')
    f.write(f'Average F1-score: {sum(f1_score_list) / len(f1_score_list):.4f}'+'\n')
    f.write(f'Average Hamming Loss: {sum(hamming_losses) / len(hamming_losses):.4f}'+'\n')


#Image Processing Assignment1: to using python to find shark in occean
#author = Minhui Chen
# DT228
# Student No: D17125347

#import package:
import numpy as np
import cv2
from matplotlib import pyplot as plt
from matplotlib import image as image
import easygui

#Reading Imgae
f = easygui.fileopenbox()
i = cv2.imread(f)

#convert BRG image to YUV
Yuv = cv2.cvtColor(i, cv2.COLOR_RGB2YUV)
y,u,v = cv2.split(Yuv)

# Values = y.ravel()
# plt.hist(Values, bins = 256, range = [0,256]);

Yequalize = cv2.equalizeHist(y)

#get new yuv image after equalize
MergeYUV = cv2.merge([Yequalize,u,v])

#covert the yuv to RGB
newImg = cv2.cvtColor(MergeYUV, cv2.COLOR_YUV2RGB)
cv2.imshow("newImg", newImg)
cv2.waitKey(0)

Vimge = cv2.add(v, 1)
cv2.imshow("Vimge", Vimge)
cv2.waitKey(0)

#using threshold to get ROI
T = np.mean(Vimge)+np.std(Vimge)
T, ROI = cv2.threshold(u, thresh = T, maxval = 255, type = cv2.THRESH_BINARY_INV)
cv2.imshow("ROI", ROI)
cv2.waitKey(0)

kernel = np.ones((3,3), np.uint8)
img_bin = cv2.erode(ROI, kernel, iterations=1)
img_bin = cv2.dilate(img_bin, kernel, iterations=2)
cv2.imshow("img_bin", img_bin)
cv2.waitKey(0)

bitwiseNOT = cv2.bitwise_not(img_bin)

Shark = cv2.bitwise_and(i,i, mask = bitwiseNOT)
Shark[bitwiseNOT == 0] =[255,255,255]
Shark = cv2.GaussianBlur(Shark, (3,3), 0)

cv2.imshow("Shark", Shark)
cv2.waitKey(0)

cv2.waitKey(0)

# =============================================================================
# k = py.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]], dtype=float)
# f = cv2.filter2D(S1,ddepth=-1, kernel = k)
# =============================================================================


from importlib.metadata import files
import os
import sys
import subprocess
import time

import verify_solution

def verify_all_solutions(
    input_file,
    input_complete_path,
    output_run_dir,
    number_of_slices,
    problem
):
    inputs = os.path.join(output_run_dir, "inputs")
    outputs = os.path.join(output_run_dir, "outputs")

    ver_file_name = os.path.join(output_run_dir, "verification.txt")
    with open(ver_file_name, "w") as v:
        pass

    slice_dir = input_file.split(".")[0]
    for i in range(number_of_slices):
        text = ""
        slice_input = input_file.split(".")[0] + "_slice_" + str(i+1) + ".json"
        slice_input_path = os.path.join(inputs, slice_input)
        slice_output = input_file.split(".")[0] + "_slice_" + str(i+1)
        sol_file_name = slice_output + "_sol_log.json"
        slice_output_path = os.path.join(outputs, slice_output, sol_file_name)

        all_sol = "-a"

        text += slice_input + "\n"
        text += verify_solution.verify(
            (slice_input_path, slice_output_path, problem, all_sol)
        )

        with open(ver_file_name, "a") as file_ver:
            file_ver.write(text)

    last_slice_output_path = os.path.join(
        output_run_dir,
        "sr_log",
        input_file.split(".")[0],
        "outputs",
        (
            input_file.split(".")[0]
            + "_"
            + str(number_of_slices)
            + "_sol.json"
        )
    )

    text = "-------------FULL SOLUTION-------------" + "\n"
    text += input_file + "\n"
    text += verify_solution.verify(
        (input_complete_path, last_slice_output_path, problem)
    )

    with open(ver_file_name, "a") as file_ver:
        file_ver.write(text)

if __name__=="__main__":
    args = sys.argv[1:]

    if (len(args) < 3):
        text = "Needs input dir with test instances,"
        text += " an output dir and the problem to be solved"
        print(text)
        exit(0)

    host_data = {
        "ip" : "127.0.0.1",
        "port" : "6464"
    }

    tests_dir = args[0]
    output_dir = args[1]
    problem = args[2]

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

    files_names = os.listdir(tests_dir)
    print(files_names)
    files_names = [
        item
        for item in files_names
        if item[-5:] ==  ".json"
    ]

    # print(tests_dir)
    print(files_names)

    # files_names = [files_names[2]]
    # files_names = files_names[:5]

    n_runs = 5

    time_limit = 600

    time_slice = 60
    number_of_slices = 10

    list_of_not_solved = os.path.join(
        output_dir,
        "not_solved.txt"
    )
    with open(list_of_not_solved, "w"):
        pass

    for i in range(n_runs):

        for file_name in files_names:

            print("=" * 80)
            print(file_name)
            run_name = file_name.split(".")[0] + "_run_" + str(i+1)
            output_run_dir = os.path.join(
                output_dir,
                run_name
            )

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

            input_file = os.path.join("..", tests_dir, file_name)

            command = ""
            command = str(sys.executable) + " "
            command += "server_requests.py "
            command += "--time-limit " + str(time_limit) + " "
            command += "--time-slice " + str(time_slice) + " "
            command += "--is-test "
            command += "--test-directly "
            command += "--test-instance " + input_file + " "
            command += "--output-location "
            command += os.path.join("..", output_run_dir) + " "

            command += "--problem " + problem

            print(command)
            print("-" * 80)

            start_time = time.time()

            server_requests_dir = os.path.join(".", "server_requests")

            sp = subprocess.Popen(
                command,
                shell=True,
                stdout=subprocess.PIPE,
                cwd=server_requests_dir
            )
            output = sp.communicate()[0]

            exit_code = sp.returncode

            print("EXEC TIME: " + str(time.time() - start_time))

            try:
                verify_all_solutions(
                    file_name,
                    os.path.join(tests_dir, file_name),
                    output_run_dir,
                    number_of_slices,
                    problem
                )
            except FileNotFoundError as ex:
                with open(list_of_not_solved, "a") as f:
                    f.write(str(run_name))
                    f.write("\n")

            print("=" * 80)


# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @FILE     : test_addmember.py
# @Author   : Pluto.
# @Time     : 2020/10/29 18:09
import allure
import pytest
import yaml

from seleniumtest.page.main_page import MainPage

def getdatas():
    datas = yaml.safe_load(open("../datas/addcontact.yml", encoding="utf-8"))
    add1 = datas["add1"]
    case1 = datas["case1"]
    addfail = datas["addfail"]
    case2 = datas["case1"]
    add2 = datas["add2"]
    case3 = datas["case3"]
    return add1, case1, addfail, case2, add2, case3

@allure.feature("添加成员模块")
class TestAddmember:
    def setup(self):
        self.main = MainPage()

    def teardown(self):
        self.main.driver.quit()

    @allure.feature("添加成员")
    @pytest.mark.parametrize("username, acctid, phone", getdatas()[0], ids=getdatas()[1])
    def test_addmember(self, username, acctid, phone):
        namelist = self.main.goto_addmember_page().addmember(username, acctid,
                                                             phone).save_addmember().get_addmember_list()
        assert username in namelist

    @allure.feature("添加成员失败")
    @pytest.mark.parametrize("username, acctid, phone", getdatas()[2], ids=getdatas()[3])
    def test_addmember_fail(self, username, acctid, phone):
        namelist = self.main.goto_addmember_page().addmember(username, acctid,
                                                             phone).cancel_member().get_addmember_list()
        assert username not in namelist

    @allure.feature("通讯录添加成员")
    @pytest.mark.parametrize("username, acctid, phone", getdatas()[4], ids=getdatas()[5])
    def test_contact_addmember(self, username, acctid, phone):
        namelist = self.main.goto_contact_page().goto_addmember_page().addmember(username, acctid,
                                                                                phone).save_addmember().get_addmember_list()
        assert username in namelist


import _rightThumb._matrix as _matrix

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

import time
def switch( name=None, switch=None, expected_input_example = None, isRequired=False, isPipe=False, description='', examples=None, required=None, related=None, isDefault=False, focus=None, trackingID=None,     f=None, printFocus=False ):
		appReg = _matrix.appReg
		if not f is None:
			focus = f

		if focus is None:
			stack = _matrix.app.c(c=1)
			try:
				focus = stack['programs'][0]
			except Exception as e:
				stack = _matrix.app.c(i=0,c=1)
				focus = stack['file']
			if focus == _matrix.app.theMatrix:
				global mainApp
				focus = mainApp

			if _matrix.printSwitcheFocus or printFocus:
				print( 'focus', focus )

		if name is None:
			name = 'Default'
			focus = 'isDefault'
		if switch is None:
			registration = None
		else:
			registration = { 'name': name, 'switches': switch, 'expected_input_example': expected_input_example, 'isRequired': isRequired, 'isPipe': isPipe, 'description': description, 'examples': examples, 'required': required, 'related': related, 'isDefault': isDefault }

		if not _matrix.app.label( name, focus ) in _matrix.app.records[ 'async' ].keys() and _matrix.app.label( name, focus, isBase=True ) in _matrix.app.records[ 'async' ].keys():
			_matrix.app.records[ 'async' ][ _matrix.app.label( name, focus ) ] = _matrix.app.records[ 'async' ][ _matrix.app.label( name, focus, isBase=True ) ]
			return _matrix.app.records[ 'async' ][ _matrix.app.label( name, focus ) ]

		_matrix.app.sequences['all'] +=1
		try:
			_matrix.app.sequences['switch']['all'] +=1
		except Exception as e:
			_matrix.app.sequences['switch']['all'] = 1

		if registration is None:
			_matrix.app.additional_Not_Registration( 'switch', name, registration, focus )
			if _matrix.app.label( name, focus ) in _matrix.app.records[ 'switch' ].keys():
				return _matrix.app.records[ 'switch' ][ _matrix.app.label( name, focus )]
			if _matrix.app.label( 'Default', 'isDefault' ) in _matrix.app.records[ 'switch' ].keys():
				return _matrix.app.records[ 'switch' ][ _matrix.app.label( 'Default', 'isDefault' ) ]

			else:
				return None
		else:
			registration['trackingID'] = trackingID
			registration['epoch'] = time.time()
			if focus is None:
				focus = appReg

			if 'isBase' in registration.keys():
				isBase = True
			else:
				isBase = False

			registration['focus'] = focus
			registration['name'] = name
			registration['hashID'] = _matrix.app.label( name, focus, isBase=isBase )

			additional = _matrix.app.additional_Registration( 'switch', name, registration )
			if not additional is None:
				registration['additional'] == additional
			try:
				_switch_child
			except Exception as e:
				from _rightThumb._matrix import _switch_child
			_matrix.app.indexes['labels']['switch'].append( name )
			theID = _matrix.app.newMasterID()

			if not _matrix.app.label( name, focus, isBase=isBase ) in _matrix.app.records[ 'switch' ].keys():
				_matrix.app.records[ 'switch' ][_matrix.app.label( name, focus, isBase=isBase )] = _switch_child.TheChild( theID=theID, registration=registration )
			elif _matrix.app.label( name, focus, isBase=isBase ) in _matrix.app.records[ 'switch' ].keys():
				_matrix.app.records[ 'switch' ][_matrix.app.label( name, focus, isBase=isBase )].add( theID=theID, registration=registration )
			return _matrix.app.records[ 'switch' ][_matrix.app.label( name, focus, isBase=isBase )]
			# _matrix.app.records_switch[name] = _switch_child.TheChild( theID=theID, registration=registration )


"""
For data visualization of results from CNN and SVM models

Creates plots to help compare the results of the CNN and SVM models
when they were tested with the 100x100, 80x80, and 40x40 images.

Dependencies:
    json
    matplotlib
    numpy
"""

import json
import matplotlib.pyplot as plt
import numpy as np

def loadJson(filePath:str):
    """
    Loads the JSON as a dictionary. Not sure what else you're expecting
    """
    with open(filePath, 'r') as f:
        jsonDict = json.load(f)
    return jsonDict

def makeMasterFile():
    """
    Compiles all the data into a single file and saves in current working directory
    """
    rescale100File = "API_Project/AWS-Rescale100x100-Labels/All-100x100-Labels.json"
    rescale80File = "API_Project/AWS-Rescale80x80-Labels/All-80x80-Labels.json"
    rescale40File = "API_Project/AWS-Rescale40x40-Labels/All-40x40-Labels.json"
    svmAndActualFile = "svmAndActual.json"

    rescale100Labels = loadJson(rescale100File)
    rescale80Labels = loadJson(rescale80File)
    rescale40Labels = loadJson(rescale40File)
    svmAndActualLabels = loadJson(svmAndActualFile)

    imgNames = list(svmAndActualLabels.keys())
    keyNames = ["actual", "aws-100x100", "aws-80x80", "aws-40x40", "svm"]

    data = dict()

    for img in imgNames:
        data[img] = {
            keyNames[0]: svmAndActualLabels[img]["Actual"],
            keyNames[1]: rescale100Labels[img],
            keyNames[2]: rescale80Labels[img],
            keyNames[3]: rescale40Labels[img],
            keyNames[4]: svmAndActualLabels[img]["Predicted"]
        }

    json_string = json.dumps(data, sort_keys=True, indent=4,
        separators=(',',':'))

    with open("master-03-31-2019.json", "w") as f:
        f.write(json_string)

def getAccuracy(data, imgNames):
    """
    Counts the number of times the model properly predicts the gender for each
    scenario.

    Args:
        data: dictionary containing the data in format saved by the masterFile()
        imgNames: file names of the images that were used in the testing

    Returns:
        A dictionary that contains the count of correct predictions for each
        test case
    """

    genderData = dict()
    genderData["actual"] = {"male":0,"female":0}
    genderData["aws-100x100"] = {"male":0,"female":0}
    genderData["svm"] = {"male":0,"female":0}
    genderData["aws-80x80"] = {"male":0,"female":0}
    genderData["aws-40x40"] = {"male":0,"female":0}
    for img in imgNames:
        try:
            if data[img]["actual"] == 1:
                genderData["actual"]["male"] += 1
                if data[img]["aws-100x100"]["FaceDetails"][0]["Gender"]["Value"] == "Male":
                    genderData["aws-100x100"]["male"] += 1
                if (data[img]["aws-40x40"]["FaceDetails"][0]["Gender"]["Value"] == "Male" or
                    len(data[img]["aws-40x40"]["FaceDetails"]) == 0):
                    genderData["aws-40x40"]["male"] += 1
                if data[img]["aws-80x80"]["FaceDetails"][0]["Gender"]["Value"] == "Male":
                    genderData["aws-80x80"]["male"] += 1
                if data[img]["svm"] == 1:
                    genderData["svm"]["male"] += 1
            else:
                genderData["actual"]["female"] += 1
                if data[img]["aws-100x100"]["FaceDetails"][0]["Gender"]["Value"] == "Female":
                    genderData["aws-100x100"]["female"] += 1
                if (data[img]["aws-40x40"]["FaceDetails"][0]["Gender"]["Value"] == "Female" or
                    len(data[img]["aws-40x40"]["FaceDetails"]) == 0):
                    genderData["aws-40x40"]["female"] += 1
                if data[img]["aws-80x80"]["FaceDetails"][0]["Gender"]["Value"] == "Female":
                    genderData["aws-80x80"]["female"] += 1
                if data[img]["svm"] == 0:
                    genderData["svm"]["female"] += 1
        except:
            pass

    return genderData

def plotGenderData(genderData):
    """
    Creates a bar graph representing the total accuracy of gender prediction of
    SVM at 100x100 and CNN at tested resolutions

    Args:
        genderData: Dictionary containing the number of correctly predicted
            genders for each model retrieved from getAccuracy()
    """
    print(genderData)
    keys = list(genderData.keys())
    keys.remove("actual")
    males = []
    females = []
    for key in keys:
        males.append(genderData[key]["male"]/genderData["actual"]["male"]*100)
        females.append(genderData[key]["female"]/genderData["actual"]["female"]*100)
    print(males)
    print(females)
    data = [males,females]

    barWidth = 0.25
    r1 = np.arange(len(males))
    r2 = [x + barWidth for x in r1]

    plt.bar(r1, males, color='c', width=barWidth, edgecolor='white',
        label='Males')
    plt.bar(r2, females, color='m', width=barWidth, edgecolor='white',
        label='Females')

    plt.xticks([r + barWidth/2 for r in range(len(keys))], ["CNN-100x100","SVM-100x100","CNN-80x80","CNN-40x40"])
    plt.ylim(0,100)
    plt.ylabel("Accuracy (%)")
    plt.grid(alpha = 200)
    plt.title("Comparing Accuracies between CNN and SVM")
    plt.legend()
    plt.show()

def getConfidences(data, imgNames):
    """
    Plots the CNN prediction confidences at the tested resolutions

    Args:
        data: dictionary containing the data in format saved by the masterFile()
        imgNames: file names of the images that were used in the testing
    """
    age = dict({"aws-100x100":[], "aws-80x80":[], "aws-40x40":[]})
    gender = dict({"aws-100x100":[], "aws-80x80":[], "aws-40x40":[]})

    for img in imgNames:
        for key in list(age.keys()):
            try:
                gender[key].append(data[img][key]["FaceDetails"][0]["Gender"]["Confidence"])
                ageHigh = data[img][key]["FaceDetails"][0]["AgeRange"]["High"]
                ageLow = data[img][key]["FaceDetails"][0]["AgeRange"]["Low"]
                age[key].append(ageHigh - ageLow)
            except:
                pass
    keys = list(age.keys())
    avgConfidence = []
    avgAgeRange = []
    for key in keys:
        avgConfidence.append(sum(gender[key])/len(gender[key]))
        avgAgeRange.append(sum(age[key])/len(age[key]))

    plt.bar(keys, avgConfidence, color = 'm')
    plt.ylabel("Confidence (%)")
    plt.ylim(0,100)
    plt.xlabel("Picture Resolution")
    plt.xticks([0,1,2],["100x100", "80x80", "40x40"])
    plt.title("Gender Prediction Confidence using a CNN")
    plt.show()

    plt.bar(keys, avgAgeRange, color = 'm')
    plt.ylabel("Predicted Age Range")
    plt.xlabel("Picture Resolution")
    plt.xticks([0,1,2],["100x100", "80x80", "40x40"])
    plt.title("Age Prediction Range")
    plt.show()

def main():
    masterFile = "master-03-31-2019.json"
    data = loadJson(masterFile)
    imgNames = list(data.keys())

    # keyNames = ["actual", "aws-100x100", "aws-40x40", "aws-80x80", "svm"]
    # print(data[imgNames[0]]["aws-100x100"]["FaceDetails"])
    plotGenderData(getAccuracy(data, imgNames))
    getConfidences(data, imgNames)

main()
# makeMasterFile()


import csv
import pickle

#Bartosz Borne
topic_index = 6 #index of the topic attribute in the questions csv file

settings = {
    "topic": "",
    "schools_attending": [],
    "year_groups_attending": []
}

def save_settings():
    with open("settings.pickle", "wb") as file:
        pickle.dump(settings, file, pickle.HIGHEST_PROTOCOL)

def load_settings():
    with open("settings.pickle", "rb") as file:
        pickle.load(file)
        return (settings)

def select_topic():
    #Create list of unique topics
    topics = []
    with open("questions.csv", newline="") as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            if row[topic_index] not in topics:
                topics.append(row[topic_index])

    while True:
        #Display list of topics
        for i in range(len(topics)):
            print(str(i+1) + ". " + topics[i])
        try:
            choice = int(input("0. Cancel\n\nSelect topic number: "))
            if choice == 0:
                break
            elif choice in range(1, len(topics)+1):
                chosen_topic = topics[choice-1]
                settings["topic"] = chosen_topic
                print("The topic is now set to: " + chosen_topic)
                break
            else:
                print("Invalid command.")
        except:
            print("Invalid command. Enter a digit.")

    save_settings()
    return(chosen_topic)
#Ianto Jones
def enterSchool():
    schoolsAttending = []
    newList = []
    newListName = []
    for school in (settings["schools_attending"]):
        print(school)
    endofSchool = False

    while endofSchool == False:
        endInput = False

        print("1. Enter School, enter 0 when you want to stop.")
        print("2. Delete School.")

        schoolChoice = input("Select choice number: ")
        if schoolChoice == "0":
            endofSchool = True
            break
        elif schoolChoice == "1":
            while endInput == False:
                schoolname = input("Enter School's name: ")
                inList = False
                while inList == False:
                    validYear = False
                    if schoolname == "0":
                        endInput = True
                        break
                    elif schoolname == "":
                        print("Must input a School name")
                        schoolname = input("Enter School name: ")
                        print("---")
                        inList = False
                    # elif schoolname in schoolsAttending:
                    #     print("Already entered: " + schoolname + " - Enter a different School name.")
                    #     schoolname = input("Enter School name: ")
                    #     print("---")
                    #     inList = False
                    else:
                        while validYear == False:
                            schoolYear = (input("Enter YearGroup of school: "))
                            if schoolYear == "":
                                print("Year must be between 1 and 13.")
                            elif int(schoolYear) < 1:
                                print("Year must be between 1 and 13.")
                            elif int(schoolYear) > 13:
                                print("Year must be between 1 and 13.")
                            else:
                                schoolsAttending.append((schoolname, int(schoolYear)))
                                print("Entered: " + schoolname)
                                print("---")
                                inList = True
                                validYear = True
                                break

        elif schoolChoice == "2":
            deleteSchool = input("Enter School's name you wish to remove: ")
            newList = [i for i in schoolsAttending if i[0] != deleteSchool]
            print("Deleted: " + deleteSchool)
            schoolsAttending = newList
        else:
            print("Invalid command.")
            print("---")

    settings["schools_attending"] = schoolsAttending
    save_settings()
    #
    #FOR TESTING WHATS IN THE LIST
    #
    #for school in (settings["schools_attending"]):
    #    print(school)
#
#FOR TESTING CODE
#
#enterSchool()
#select_topic()


# works only sometimes don't know why
# http://timisoaractf.ro [ CTF Website ]
import socket

def get_encoding(byte):
    h = hex(byte%0xff)[2:]
    if len(h) == 1: h = "0"+h
    return h

# Connection and Banner Print
s = socket.socket()
s.connect(("89.38.208.143", 21022))
m = s.recv(1024).decode()
print(m)

# Get the cipher to decode
cipher = m[-83:-57].strip().split()

i = 0
decipher = []
while i < 8:
    decipher_text = "".join(decipher) # decipher text to encrypt
    print("decipher text:", decipher_text+"!")
    s.send((decipher_text+"!\n").encode())
    enc = s.recv(1024).decode() # recv encrypted text
    print(enc)
    enc_byte = int(enc[i*3+18:i*3+20].strip(), 16) # extract latest byte to bruteforce
    print("encrypted_byte:", hex(enc_byte)[2:])
    local_enc_byte = get_encoding(enc_byte)

    # Brute force by incrementing byte by 8 and checking against corresponding cipher value
    for j in range(94): # only printable chars
        if cipher[i] != local_enc_byte:
            #print("[-] {}".format(local_enc_byte))
            enc_byte += 0x8
            local_enc_byte = get_encoding(enc_byte)
        else:
            decipher.append(chr(ord("!")+j))
            break

    # found deciphered character
    print("[+] {}: {}\n".format(cipher[i], decipher[i]))
    i += 1

# sending bytes of the deciphered text
s.send(b"\n")
decipher = "".join(decipher)+"\n"
print(decipher.encode())
m = s.recv(1024).decode()
print(m)
s.send(decipher.encode())
print(s.recv(1024).decode())


# %%
import numpy as np
import os
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import pickle
from scipy.stats import multivariate_normal

# %%
def draw_heatmap(mux, muy, sx, sy, rho, ax, bound=1):
    x, y = np.mgrid[slice(mux - bound, mux + bound, 0.01),
                    slice(muy - bound, muy + bound, 0.01)]

    mean = [mux, muy]

    # Extract covariance matrix
    cov = [[sx * sx, rho * sx * sy], [rho * sx * sy, sy * sy]]

    gaussian = multivariate_normal(mean = mean, cov = cov)
    d = np.dstack([x, y])
    z = gaussian.pdf(d)

    z_min, z_max = -np.abs(z).max(), np.abs(z).max()

    ax.pcolormesh(x, y, z, cmap='bwr', vmin=z_min, vmax=z_max, alpha=1) # cmap='PiYG'

# %%
def visual(data_file=None):

    # if no specific data_file, choose the latest one
    if data_file is None:
        result_dir = "./results/"
        lists = os.listdir(result_dir)
        lists.sort(key=lambda fn: os.path.getmtime(result_dir+"/"+fn))
        data_file = os.path.join(result_dir, lists[-1])

    f = open(data_file, "rb")
    visual_data = pickle.load(f)
    f.close()

    pred_trajs   = visual_data[0] # list(array(seq_length, 2))
    truth_trajs  = visual_data[1] # list(array(seq_length, 2))
    gauss_params = visual_data[2] # list(array(pred_length, 5))
    obs_length = int(pred_trajs[0].shape[0] - gauss_params[0].shape[0])

    traj_num = len(pred_trajs)

    fig_width, fig_height = 5, 5

    fig, ax = plt.subplots(1,1,figsize=(fig_width, fig_width))

    x_min = min(np.array(truth_trajs)[:, :, 0].min(), np.array(pred_trajs)[:, :, 0].min())-0.1
    x_max = max(np.array(truth_trajs)[:, :, 0].max(), np.array(pred_trajs)[:, :, 0].max())+0.1
    y_min = min(np.array(truth_trajs)[:, :, 1].min(), np.array(pred_trajs)[:, :, 0].min())-0.1
    y_max = max(np.array(truth_trajs)[:, :, 1].max(), np.array(pred_trajs)[:, :, 0].max())+0.1

    for index in range(traj_num):
        ax.set_xlim(x_min, x_max)
        ax.set_ylim(y_min, y_max)
        ax.set_title("Predict %3s out of %s trajectories" % (index+1,traj_num ))
        visual_trajectories(pred_trajs[index], truth_trajs[index], gauss_params[index], obs_length, ax)
        plt.cla()
        # plt.pause(5)

def visual_trajectories(pred_trajs, true_traj, gauss_param, obs_length, ax):
    colors = plt.cm.Set3(np.linspace(0, 1, 12))
    if true_traj is None:
        for pred in range(gauss_param.shape[1]):
            for traj_id in range(gauss_param.shape[0]):
                # plot predicted traj
                ax.plot(pred_trajs[traj_id, 0:obs_length+pred+1, 0], pred_trajs[traj_id, 0:obs_length+pred+1, 1],
                        color=colors[traj_id], linestyle='-', linewidth=1,marker='o', markersize=2,
                        markeredgecolor=colors[traj_id], markerfacecolor=colors[traj_id])

                draw_heatmap(*gauss_param[traj_id,pred,:], ax=ax, bound=1.5)
                plt.pause(0.1)

    else:
        for pred in range(gauss_param.shape[0]):
            # plot predicted traj
            ax.plot(pred_traj[0:obs_length+pred+1, 0], pred_traj[0:obs_length+pred+1, 1],
                    color = 'g', linestyle = '-', linewidth = 1,
                    marker = 'o', markersize = 2, markeredgecolor = 'g', markerfacecolor = 'g')
            # plot ground truth traj
            ax.plot(true_traj[0:obs_length+pred+1, 0], true_traj[0:obs_length+pred+1, 1],
                    color = 'r', linestyle = '-', linewidth = 1,
                    marker = 'o', markersize = 1, markeredgecolor = 'r', markerfacecolor = 'r')

            draw_heatmap(*gauss_param[pred], ax=ax, bound=1.2)
            plt.pause(0.01)

def visual_for_real(pred_trajs, gauss_params):
    """visualization for real test, instead of testing in dataset

    Args:
        pred_trajs  (3D-array): array(batch_size, seq_length, 2))
        gauss_param (3D-array): array(batch_size, pred_length, 5)
    """

    obs_length = int(pred_trajs.shape[1] - gauss_params.shape[1])

    traj_num = pred_trajs.shape[0]

    fig_width, fig_height = 5, 5

    fig, ax = plt.subplots(1,1,figsize=(fig_width, fig_width))

    x_min = np.array(pred_trajs)[:, :, 0].min()-0.1
    x_max = np.array(pred_trajs)[:, :, 0].max()+0.1
    y_min = np.array(pred_trajs)[:, :, 1].min()-0.1
    y_max = np.array(pred_trajs)[:, :, 1].max()+0.1

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_max)
    visual_trajectories(pred_trajs, None, gauss_params, obs_length, ax)
    plt.cla()
    # plt.pause(5)

if __name__=="__main__":
    visual()

# %%


from django.urls import include, path
from .views import discord_callback, ListGuildChannels, ListScheduledMessages, ListChannelScheduledMessages

urlpatterns = [
    path("api/guilds/<str:guild_id>/channels", ListGuildChannels.as_view(), name="list-guild-channels"),
    path("api/guilds/<str:guild_id>/scheduled-messages", ListScheduledMessages.as_view(), name="list-scheduled-messages"),
    path("api/channels/<int:channel_id>/scheduled-messages", ListChannelScheduledMessages.as_view(), name="list-channel-scheduled-messages"),
    path("discord/callback", discord_callback, name="discord-callback"),
]


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
	# Examples:
	url(r'^$', 'axolotl.views.home', name='home'),
	# url(r'^axolotl/', include('axolotl.foo.urls')),

	# Uncomment the admin/doc line below to enable admin documentation:
	url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

	# Uncomment the next line to enable the admin:
	url(r'^admin/', include(admin.site.urls)),
	#(r'^accounts/', include('invitation.urls')),
	#url(r'^accounts/', include('registration.backends.default.urls')),
	url(r'^accounts/profile/', 'axolotl.views.profile', name='profile'),
	url(r'^accounts/login/$', 'django.contrib.auth.views.login', {
			'template_name': 'login.html'
	}, name="login"),
	url(r'^accounts/logout/$', 'django.contrib.auth.views.logout_then_login',
		name="logout"),

	url(r'^bitsync/', include('bitsync.urls')),
	url(r'^tv/', include('tv.urls')),

)


"""justBlog URL Configuration

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

urlpatterns = [
    path('manage/', views.manage),#后台管理
    path('user/', views.user),#用户管理
    path('login/', views.login),#登录管理
    path('index/', views.index), #主页
    path('about/', views.about), #关于
    path('article/', views.article), #文章api-restful
    path('upload/', views.upload), #上传api
    path('article/list/', views.articlelist), #文章列表api
    path('message/', views.messageBoard),#留言api
    path('broadcast/', views.broadcast), #公告api
    path('comment/', views.comment), #评论api
    path('zan/', views.good), #评论api
    path('article/<int:articleid>.html', views.details),#文章详情页
    path('test/', views.test),
]


"""
Local run for Node ExpressJS (backend) application
"""
from rich.console import Console
from rich.traceback import install

from commands.seed import ui_seed
from commands.yarn import ui_yarn
from flavours.shared import (
    copy_artifacts_from_dind,
    pull_and_build_images,
    start_services,
    yarn_build,
    yarn_install,
)
from lib.dekickrc import get_dekickrc_value

install()
console = Console()

def main():
    """Main"""
    pull_and_build_images()
    yarn_install()
    copy_artifacts_from_dind()
    yarn_build()
    start_services()
    if get_dekickrc_value("dekick.settings.seed.local") is True:
        ui_seed(force=True)
    ui_yarn(args=["test"])


from pyspark.sql import SparkSession
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import StringType, IntegerType, DateType
import numpy as np

spark = SparkSession.builder.master("local").appName('Filter Something').getOrCreate()

schema = StructType([StructField('id', IntegerType(), True),  # name col, data type, is nullable?
                     StructField('num', IntegerType(), True),
                     StructField('num2', IntegerType(), True)
                    ])

# Create DF with defined schema
df = spark.createDataFrame([[1,None,3],
                            [4,5,None],
                            [None,7,8]], schema)

df.show()

# df.na.drop().show()  # Eliminate row if it one column contains a null value  (note: "how=any" by default)

# df.na.drop(how='all').show() #Eliminate column if all columns contain a null value

#df.na.drop(how='any', subset=['num','num2']).show() # Eliminate rows if contains any null value in num and num2 columns

# df.na.fill(0).show() # fill all null values witj zero

# df.na.fill(0,['num','num2']).show() # fill a value in columns specified

# df.na.fill({'id':4, 'num2': 100})

# df.na.replace(8, 99).show() # replace a value with other.

# df.na.replace({8: 99}).show() # replace a value with other.

# df.na.replace([8,1],[99,99]).show() # replace  list vs list

# df.na.replace([5,7],[99,99], subset=['num']).show() # replace  list vs list in a column specified

spark.stop()


from . import TrackingService, unescape, untagify

import re
from dateutil.parser import parse as parsedate

class OnTracComService(TrackingService):
    """OnTrac"""

    name = "OnTrac"
    url = 'https://www.ontrac.com/trackingres.asp?tracking_number=%(number)s'

    def _get_page(self):
        page = super(OnTracComService, self)._get_page().decode('utf-8', 'ignore')
        res = re.search('trackingdetail\.asp\?[^"]+', page)
        if res is None:
            return ""
        return self._fetch_url("https://www.ontrac.com/" + res.group(0), None, {})

    def _parse_page(self, html):
        html = html.decode('utf-8', 'ignore')
        res = re.search('
.*?(.*?)
', html, re.DOTALL | re.UNICODE)
        if res is None:
            return []
        html = res.group(1)
        result = []
        for res in re.findall('
]*?>\s*<td[^<]*?
(.*?)	\s*<td[^<]*?
(.*?)	\s*<td[^<]*?
(.*?)	', html, re.DOTALL | re.UNICODE):
            action, date, location = (untagify(unescape(x)).strip() for x in res)
            date = parsedate(date)
            result.append((action, date, location))
        return result


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Create Date    :  2017-08-17 12:08
# Git Repo       :  https://github.com/Jerry-Ma
# Email Address  :  jerry.ma.nk@gmail.com
"""
common.py
"""

from __future__ import (absolute_import, division, print_function)
from functools import wraps
import os

def get_log_func(default_level='debug', **kwargs):
    """return a convenient logger function"""
    logger = kwargs.pop('logger', None)
    logger_mutex = kwargs.pop('logger_mutex', None)

    def logfunc(*args):
        if len(args) == 1:
            level, mesg = default_level, args[0]
        else:
            level, mesg = args
        if logger_mutex is None or logger is None:
            print("[{0}] {1}".format(level, mesg))
        else:
            with logger_mutex:
                getattr(logger, level)(mesg)
    return logfunc

def touch_file(out_file):
    with open(out_file, 'a'):
        os.utime(out_file, None)

def create_symbolic_link(in_file, out_file, **kwargs):
    """create relative symbolic link

    :in_file: filename of original file
    :out_file: filename of symlink to create

    """
    # print(in_file)
    # print(out_file)
    log = get_log_func(**kwargs)
    in_file = os.path.abspath(in_file)
    out_file = os.path.abspath(out_file)
    in_dir = os.path.dirname(in_file)
    out_dir = os.path.dirname(out_file)
    if kwargs.get('relpath', True):
        src_path = os.path.relpath(in_file, out_dir)
    else:
        src_path = os.path.abspath(in_file)
    log('info', 'link {0} -> {1}'.format(src_path, out_file))
    if in_dir == out_dir or in_file == out_file:
        raise RuntimeError('target and source are from the same directory {0}'
                           .format(in_dir))
    if os.path.lexists(out_file):
        if not os.path.islink(out_file):
            raise RuntimeError("%s exists and is not a link" % out_file)
        try:
            os.unlink(out_file)
        except Exception as e:
            log('info', 'cannot unlink {0}: {1}'.format(out_file, e))
    os.symlink(src_path, out_file)


import logging
import json
from django.http import HttpResponse
from django.views import View
from django_client_logger.logger import process_log_message
from userservice.user import UserService

logger = logging.getLogger(__name__)

class LogReceiver(View):
    def post(self, request, *args, **kwargs):
        original_user = UserService().get_original_user()
        override_user = UserService().get_override_user()
        session_key = request.session.session_key
        body = request.POST
        try:
            data = body.get('data')
            process_log_message(json.loads(data), session_key,
                                original_user, override_user)
        except Exception as ex:
            logger.error('Failed to process log messages: {}, "{}"'.format(
                str(ex), data))
        return HttpResponse('')


#mcandrew

import sys
import numpy as np
import pandas as pd

from delphi_epidata import Epidata
from epiweeks import Week, Year
import datetime

def fromDateTime2EW(dt):
    w = Week.fromdate(dt.year,dt.month,dt.day)
    return "{:4}{:2}".format(w.year,w.week)

def createAllRegions():
    return ['nat'] + [ 'HHS{:d}'.format(n) for n in np.arange(1,10+1)]

def computeEpiWeeksWithData(firstWeekOfSeason):
    thisWeek  = datetime.datetime.today()
    _1Week    = datetime.timedelta(days=7)

    week    = firstWeekOfSeason
    epiWeeks = [fromDateTime2EW(firstWeekOfSeason)]
    while week<thisWeek:
        week = week + _1Week
        epiWeeks.append(fromDateTime2EW(week))
    epiWeeks = epiWeeks[:-2] # ILINET is 2 weeks behind the current Epidemic Week.
    return epiWeeks

def timeStamp():
    return datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

if __name__ == "__main__":

    firstWeekOfSeason = datetime.datetime.strptime('2019-10-01',"%Y-%m-%d")
    epiWeeks = computeEpiWeeksWithData(firstWeekOfSeason)
    regions = createAllRegions()

    fluData = Epidata.fluview(regions = regions ,epiweeks = epiWeeks)
    if fluData['message'] != 'success':
        print('could not download data')
        sys.exit()

    mostRecentEpiData = {'EW':[],'region':[],'wili':[]}
    for data in fluData['epidata']:
        mostRecentEpiData['EW'].append(data['epiweek'])
        mostRecentEpiData['region'].append(data['region'])
        mostRecentEpiData['wili'].append(data['wili'])
    mostRecentEpiData = pd.DataFrame(mostRecentEpiData)

    mostRecentEpiData.to_csv('./historicalData/epiData_{:s}.csv'.format(timeStamp()),index=False)
    mostRecentEpiData.to_csv('./data/epiData.csv',index=False)


# https://stackoverflow.com/questions/4214936/how-can-i-get-the-values-of-the-locals-of-a-function-after-it-has-been-executed
# author: Niklas R
import sys, types, inspect
def call_function_get_frame(func, *args, **kwargs):
  """
  Calls the function *func* with the specified arguments and keyword
  arguments and snatches its local frame before it actually executes.
  """

  frame = None
  trace = sys.gettrace()
  def snatch_locals(_frame, name, arg):
    nonlocal frame
    if frame is None and name == 'call':
      frame = _frame
      sys.settrace(trace)
    return trace
  sys.settrace(snatch_locals)
  try:
    result = func(*args, **kwargs)
  finally:
    sys.settrace(trace)
  return frame, result

class Proxy:
  def __iter__(self): return self.step()
  def __next__(self): return next(self.__it__)

def get_module(func):
  frame, result = call_function_get_frame(func)
  try:
    module = Proxy()
    module.__dict__.update(frame.f_locals)
    return module
  finally:
    del frame

def sub_scene(func):
  module = get_module(func)
  if not hasattr(module, "step"):
    return module
  module.__it__ = iter(module)
  module.step = lambda : next(module.__it__)
  return module

def cluster(func):
  module = get_module(func)
  module.__iter__ = module.__dict__.values().__iter__
  return module

@cluster
def thing():
  eggs = 'spam'
  class Bar:
    def hello(self):
      print("Hello, World!")

def unpack(ns):
    return rf"""
for k,v in {ns}.items():
    exec(f"{{k}} = {{v}}")
"""

def inline(func):
    src = inspect.getsource(func).split('\n')
    for cut,ch in enumerate( src[1] ):
        if ch not in " \t":
            break
    return '\n'.join(ln[cut:] for ln in src[1:])

if __name__ == "__main__":
    assert thing.eggs == 'spam'
    thing.Bar().hello()


# 屏幕宽高
# Screen width and height
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720

# 地板高度
# Floor height
GROUND_HEIGHT = 680

# 下落重力加速度
# Acceleration of falling gravity
GRAVITY = 0.9
# 上升重力加速度
# Upward gravitational acceleration
ANTI_GRAVITY = 0.4
# 最大行走速度（不能超过这个数值）
# Maximum travel speed (cannot exceed this value)
MAX_WALK_SPEED = 6
# 最大y轴速度
# Maximum y-axis speed
MAX_Y_SPEED = -17
# 行走加速度
# Walking acceleration
WALK_ACCEL = 0.5
# 转向加速度
# Steering acceleration
TRUN_ACCEL = 0.8
# 转向加速度
# Steering acceleration
TRUN_ACCEL = 1
# 背景放大倍数
# Background magnification
BG_MULTI = 1.5

# 主界面button缩放尺寸
# Main screen button zoom size
MAIN_BUTTON_RATE = 0.7
# 背景缩放
# Background scaling
BG_MULIT = 1.6

# 玩家贴图偏移
# Player mapping offsets
PLAYER_TEXTURE_OFFSET_X = -100
PLAYER_TEXTURE_OFFSET_Y = -69
# 玩家血量
# Player Blood
PLAYER_HP = 1500
# 玩家盒子宽高
# Player box width and height
PLAYER_RECT_WIDTH = 102
PLAYER_RECT_HEIGHT = 196
# 玩家攻击盒子宽高
# Player attack box width and height
PLAYER_ATTACK_WIDTH = 100
PLAYER_ATTACK_HEIGHT = 180
# 玩家攻击力
# Player Attack Power
PLAYER_ATTACK_VALUE = 300

# 敌人血量
# Enemy blood
ENEMY_HP = 700

# 敌人盒子宽高
# Enemy box width height
ENEMY_RECT_WIDTH = 102
ENEMY_RECT_HEIGHT = 196

# 敌人贴图偏移
# Enemy mapping offset
ENEMY_TEXTURE_OFFSET_X = -100
ENEMY_TEXTURE_OFFSET_Y = -69

# 敌人攻击力
# Enemy attack power
ENEMY_ATTACK_VALUE = 100

# 敌人巡逻速度
# Enemy patrol speed
ENEMY_WALK_SPEED = 1

# 敌人索敌速度
# Enemy Soldier Speed
ENEMY_FOLLOW_SPEED = 2

#Font
FONT='./assets/font/PangMenZhengDaoCuShuTi.ttf'


def miniMaxSum(arr):
    max_value = 0
    min_value = arr[0]
    res = 0
    for i in range(len(arr)):
        res += arr[i]
        if arr[i] > max_value:
            max_value = arr[i]
        if arr[i] < min_value:
            min_value = arr[i]
    print(f"{res-max_value} {res-min_value}")


import itertools as it

inp = [x.strip() for x in open('input.txt').readlines()]

def parse():
    retval = []
    for line in inp:
        parts = line.split(' ')
        base = parts.pop(0)
        weight = int(parts.pop(0)[1:-1])
        subs = []
        if parts:
            assert parts[0] == '->'
            parts.pop(0)
        if parts:
            for p in parts:
                p = p.replace(',', '')
                assert ',' not in p
                subs.append(p)
        retval.append((base, weight, subs))
        #print(retval[-1])
    return retval

def star1():
    d = {}
    names = set()
    for name, weight, subs in parse():
        names.add(name)
        for sub in subs:
            d.setdefault(sub, [])
            d[sub].append(name)
            names.add(sub)
    for name in names:
        if not d.get(name):
            print(name)
    return

def star2():
    names = set()
    weights = {}
    defs = {}
    for name, weight, subs in parse():
        names.add(name)
        weights[name] = weight
        defs[name] = []

    for name, weight, subs in parse():
        for sub in subs:
            defs[name] = subs

    print("WEIGHT",weights['jdxfsa'])  # this is the one that fails the assert
    for i in range(200):
        print("LEN", len(defs))
        for name, subs in list(defs.items()):
            if all(defs.get(sub, []) == [] for sub in subs):
                subw = [weights[sub] for sub in subs]
                assert all(w == subw[0] for w in subw), list(zip(subw, subs))
                weights[name] += sum(subw)
                for subn in subs:
                    defs.pop(subn, None)
                defs[name] = []
    print(defs)

if __name__ == '__main__':
    star1()
    star2()


import os
from avocado import Test
from avocado import skipUnless
from avocado.utils import process, distro, genio, dmesg
from avocado.utils.software_manager.manager import SoftwareManager

IS_POWER_NV = 'PowerNV' in genio.read_file('/proc/cpuinfo').rstrip('\t\r\n\0')

class PerfCoreIMCEvents(Test):

    """
    Checking core, thread, trace IMC events
    :avocado: tags=privileged,perf
    """

    @skipUnless(IS_POWER_NV, "This test is for PowerNV")
    def setUp(self):
        '''
        Install the basic packages to support perf
        '''

        smg = SoftwareManager()
        dist = distro.detect()
        if dist.name in ['Ubuntu', 'debian']:
            linux_tools = "linux-tools-" + os.uname()[2][3]
            pkgs = [linux_tools]
            if dist.name in ['Ubuntu']:
                pkgs.extend(['linux-tools-common'])
        elif dist.name in ['centos', 'fedora', 'rhel', 'SuSE']:
            pkgs = ['perf']
        else:
            self.cancel("perf is not supported on %s" % dist.name)

        for pkg in pkgs:
            if not smg.check_installed(pkg) and not smg.install(pkg):
                self.cancel(
                    "Package %s is missing/could not be installed" % pkg)

        # running some workload in background
        process.run("ppc64_cpu --frequency -t 10 &", shell=True,
                    ignore_status=True, verbose=True, ignore_bg_processes=True)

        # collect all imc events
        self.list_core_imc = []
        self.list_thread_imc = []
        self.list_trace_imc = []
        for line in process.get_command_output_matching('perf list', 'imc'):
            line = "%s" % line.split()[0]
            if 'core_imc' in line:
                self.list_core_imc.append(line)
            elif 'thread_imc' in line:
                self.list_thread_imc.append(line)
            elif 'trace_imc' in line:
                self.list_trace_imc.append(line)

        # Clear the dmesg, by that we can capture delta at the end of the test
        dmesg.clear_dmesg()

    def parse_op(self, cmd):
        # helper function to run events and check for failure
        fail_count = 0
        result = process.run(cmd, shell=True, sudo=True)
        output = result.stdout.decode() + result.stderr.decode()
        if ("not counted" in output) or ("not supported" in output):
            fail_count = fail_count + 1
        if fail_count > 0:
            self.fail("%s : command failed" % cmd)

    def imc_events(self, event):
        # helper function to parse different imc events
        for line in event:
            if line in self.list_core_imc:
                cmd = "perf stat -e %s -I 1000 sleep 5" % line
                self.parse_op(cmd)
            # running thread_imc events with workload
            if line in self.list_thread_imc:
                cmd = "perf stat -e %s -I 1000 ls -R /usr/ > /dev/null" % line
                self.parse_op(cmd)
            # running trace_imc events with record/report and
            # validating perf.data samples
            if line in self.list_trace_imc:
                cmd = "perf record -o perf.data -e %s -C 0 sleep 5" % line
                process.run(cmd, shell=True, sudo=True)
                res = process.run(
                    "perf report --stdio -i perf.data", shell=True, sudo=True)
                if "data has no samples!" in res.stderr.decode():
                    self.fail("trace_imc perf.data sample not captured")

    def test_core_imc(self):
        # test function to run each imc events in the list
        for event in [self.list_core_imc, self.list_thread_imc,
                      self.list_trace_imc]:
            self.imc_events(event)

        # negative testcase running two different imc events parallely
        process.run("perf stat -e core_imc/CPM_CCYC/ -I 1000 &",
                    sudo=True, shell=True, ignore_bg_processes=True)
        if not process.system("perf stat -e thread_imc/CPM_CCYC/ -I 1000 ls",
                              ignore_status=True, sudo=True):
            self.fail("test failed because able to run two different imc "
                      "events parallely")

    def tearDown(self):
        # kill process running in background
        process.system("pkill perf", ignore_status=True)
        process.system('pkill ppc64_cpu', ignore_status=True)
        # remove perf.data file generated from perf record
        if os.path.isfile("perf.data"):
            process.run('rm -f perf.data')
        # Collect the dmesg
        dmesg.collect_dmesg()


import pandas as pd
import numpy as np
import os
'''数据处理，训练集，测试集，验证集的分割
   embedding网络和ac网络
'''

ROOT_DIR = os.getcwd()
DATA_DIR = os.path.join(ROOT_DIR, 'ml-1m/')
STATE_SIZE = 10
# 加载数据
ratings_list = [i.strip().split("::") for i in open(os.path.join(DATA_DIR, 'ratings.dat'), 'r').readlines()]
users_list = [i.strip().split("::") for i in open(os.path.join(DATA_DIR, 'users.dat'), 'r').readlines()]
movies_list = [i.strip().split("::") for i in
               open(os.path.join(DATA_DIR, 'movies.dat'), encoding='latin-1').readlines()]

# 用户对电影的评价dataframe，用户id，电影id，评分，时间戳
ratings_dataframe = pd.DataFrame(ratings_list, columns=['UserID', 'MovieID', 'Rating', 'Timestamp'], dtype=np.uint32)
# 电影数量3883
movies_list_len = len(movies_list)
# 空值数量，无，数据已经清洗过
null_sum = ratings_dataframe.isnull().sum()
print(len(set(ratings_dataframe["UserID"])) == max([int(i) for i in set(ratings_dataframe["UserID"])]))
print(max([int(i) for i in set(ratings_dataframe["UserID"])]))
ratings_dataframe = ratings_dataframe.applymap(int)
ratings_dataframe = ratings_dataframe.apply(np.int32)

# '''ac网络'''
# # 电影id对应的电影信息，字典键是电影id，值是电影信息列表，传进环境里可以检查电影名
# movies_id_to_movies = {movie[0]: movie[1:] for movie in movies_list}
# np.save("./data/movies_id_to_movies.npy", movies_id_to_movies)
#
#
# # 按用户顺序整理记录用以ac网络
# users_dict = {user: [] for user in set(ratings_dataframe["UserID"])}
# # 按时间排序
# ratings_dataframe = ratings_dataframe.sort_values(by='Timestamp', ascending=True)
#
# users_dict1 = {user: [] for user in set(ratings_dataframe["UserID"])}
#
# # 好评历史长度
# ratings_df_gen = ratings_dataframe.iterrows()
# users_dict_for_history_len = {user: [] for user in set(ratings_dataframe["UserID"])}
# users_dict_for_positive_history_len = {user: [] for user in set(ratings_dataframe["UserID"])}
# for data in ratings_df_gen:
#     users_dict[data[1]['UserID']].append((data[1]['MovieID'], data[1]['Rating']))
#     users_dict_for_history_len[data[1]['UserID']].append((data[1]['MovieID'], data[1]['Rating']))
#     if data[1]['Rating'] >= 4:
#         users_dict_for_positive_history_len[data[1]['UserID']].append((data[1]['MovieID'], data[1]['Rating']))
# # 每个用户的观影历史长度，共6040个用户
# users_history_lens = [len(users_dict_for_history_len[u]) for u in set(ratings_dataframe["UserID"])]
# # 每个用户的好评观影历史长度，共6040个用户
# users_positive_history_lens = [len(users_dict_for_positive_history_len[u]) for u in set(ratings_dataframe["UserID"])]
#
#
# #无后缀
# # 用以训练ac网络，全集
# # 每个用户的观影记录（键值对，键：用户id   值：元祖（电影和评分）组成的列表）,好评差评都包括，全集
# np.save("data/users_history_dict.npy", users_dict)
# # 用户的历史长度列表全集(用户1有53条记录历史45条好评，53)
# np.save("./data/users_history_lens.npy", users_history_lens)
# # 用户的好评历史长度列表(依次序)非全集(用户1有53条记录历史45条好评，45)
# np.save("./data/users_positive_history_lens.npy", users_positive_history_lens)
# # 6041，用户总数是6040
# users_num = max(ratings_dataframe["UserID"]) + 1
# # 3953，电影总数是3952
# items_num = max(ratings_dataframe["MovieID"]) + 1
#
#
# # _train
# #训练集
# # 4832
# users_num_train = int(users_num * 0.8)
# # 3953
# items_num_train = items_num
# users_dict_train = {k: users_dict[k] for k in range(1, users_num_train + 1)}
# np.save("./data/users_dict_train.npy", users_dict_train)
# users_history_lens_train = users_history_lens[:users_num_train]
# np.save("./data/users_history_lens_train.npy", users_history_lens_train)
# users_positive_history_lens_train = users_positive_history_lens[:users_num_train]
# np.save("./data/users_positive_history_lens_train.npy", users_positive_history_lens_train)
#
# # _eval
# # 测试集
# users_num_eval = int(users_num * 0.2)
# items_num_eval = items_num
# users_dict_eval = {k: users_dict[k] for k in range(users_num-users_num_eval, users_num)}
# np.save("./data/users_dict_eval.npy", users_dict_train)
# users_history_lens_eval = users_positive_history_lens[users_num - users_num_eval - 1:]
# np.save("./data/users_history_lens_eval.npy", users_history_lens_eval)
# users_positive_history_lens_eval = users_positive_history_lens[users_num - users_num_eval - 1:]
# np.save("./data/users_positive_history_lens_eval.npy", users_positive_history_lens_eval)

'''用以embedding网络'''
# 用户对电影的评价dataframe，用户id，电影id，评分，转化为好评对后预训练embedding用
user_movie_rating_dataframe = ratings_dataframe[['UserID', 'MovieID', 'Rating']]
user_movie_rating_dataframe = user_movie_rating_dataframe.apply(np.int32)
# 筛选出评分>3的好评记录(drop掉差评记录)，需要pairs和dict
index_negative = user_movie_rating_dataframe[user_movie_rating_dataframe['Rating'] < 4].index
positive_rating_df = user_movie_rating_dataframe.drop(index_negative)
positive_u_m_pairs = positive_rating_df.drop('Rating', axis=1).to_numpy()
np.save("./data/positive_u_m_pairs.npy", positive_u_m_pairs)
positive_user_movie_dict = {u: [] for u in range(1, max(positive_rating_df['UserID']) + 1)}
for data in positive_rating_df.iterrows():
    positive_user_movie_dict[data[1][0]].append(data[1][1])
np.save("./data/positive_user_movie_dict.npy", positive_user_movie_dict)

# 筛选出和ac网络统一的训练记录(drop掉>train_users_num的记录)，pairs和dict  （_train）
index_none_train = positive_rating_df[positive_rating_df['UserID'] > 4832].index
positive_rating_df_train = positive_rating_df.drop(index_none_train)
positive_u_m_pairs_train = positive_rating_df_train.drop('Rating', axis=1).to_numpy()
np.save("./data/positive_u_m_pairs_train.npy", positive_u_m_pairs_train)
positive_user_movie_dict_train = {u: [] for u in range(1, max(positive_rating_df_train['UserID']) + 1)}
for data in positive_rating_df_train.iterrows():
    positive_user_movie_dict_train[data[1][0]].append(data[1][1])
np.save("./data/positive_user_movie_dict_train.npy", positive_user_movie_dict_train)


import sys

sys.setrecursionlimit(10**6)
input = sys.stdin.readline
cnt = 0

def recursion(s, l, r):
    global cnt
    if l >= r: return 1
    elif s[l] != s[r]: return 0
    else:
        cnt += 1
        return recursion(s, l+1, r-1)

def isPalindrome(s):
    global cnt
    cnt += 1
    return recursion(s, 0, len(s)-1)

n = int(input())

for _ in range(n):
    cnt = 0
    s = input().strip()
    print(isPalindrome(s), end=' ')
    print(cnt)


'''
Baseline Model Agent
Author: Yuya Jeremy Ong (yjo5006@psu.edu)
'''
from __future__ import print_function
import sys
import numpy as np
from scipy import stats
from sklearn.model_selection import KFold
from scipy.integrate import quad

from models.base import BaseAgent
from utils.data import DataLoader
from utils.scores import ScoreReport

def integrand(t, a, b):
    return np.exp(-t/b) * (t ** (a-1))

class GammaModel:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def pred(self, X):
        predList = []
        for x in X:
            pred = self.c * quad(integrand, 0, x, args=(self.a, self.b))[0] / ((self.b ** self.a) * np.random.gamma(self.a))
            predList.append(pred)

        return predList

class Agent(BaseAgent):
    def __init__(self, config, logger):
        self.config = config
        self.report = logger

    def run(self):
        # Load Dataset
        dl = DataLoader(self.config)
        X, y = dl.load_data()

        # Train Model - No Training Required, Just KF Validation
        self.train(X, y)

        # Generate Predictions
        self.predict(X, y)

    def train(self, X, y):
        # Initialize KF-Cross Validation
        kf = KFold(n_splits=10)
        for train_index, test_index in kf.split(X.values):
            # Extract Training Data
            X_train = np.take(X.values, train_index)
            Y_train = np.take(y.values, train_index)

            # Train Model
            model = self.train_model(X_train, Y_train)

            # Validation Inference
            X_valid = np.take(X.values, test_index)
            Y_valid = np.take(y.values, test_index)

            y_actual, y_binary, y_prob = self.validate_model(model, X_valid, Y_valid)
            self.report.append_result(y_actual, y_binary, y_prob)

    def train_model(self, X, y):
        return GammaModel(self.config.a, self.config.b, self.config.c)

    def validate_model(self, model, X, y):
        y_prob = model.pred(X)
        y_binary = [0 if p <= 0.5 else 1 for p in y_prob]
        return y, y_binary, y_prob

    def predict(self, X, y):
        model = GammaModel(self.config.a, self.config.b, self.config.c)
        y_prob = model.pred(X)
        y_binary = [0 if p <= 0.5 else 1 for p in y_prob]

        return y, y_binary, y_prob

    def finalize(self):
        # Finalize Report
        self.report.generate_rocplot()
        self.report.generate_score_report()


from django.urls import path
from .views import main, list_pat_part_two, data_page
from InternalStructure.models import WhoDirected, MedicalInstitution, TreatmentResult, InternalStructure, DeliveryTime, \
    Autopsy, GroupOperation
from InternalStructure.forms import WhoDirectedForms, MedicalInstitutionForms, TreatmentResultForms, \
    InternalStructureForms, DeliveryTimeForms, AutopsyForms, GroupOperationForms
from ListOfPatients.models import ListPatView, ListPatPageOne
from ListOfPatients.forms import ListPatViewForms, ListPatPageOneForms, FilterForms

urlpatterns = [
    path('', main, name='main'),
    # "Движение"->"Движение по датам"
    path('list_move/', data_page, {'model': ListPatPageOne, 'rec_form': ListPatPageOneForms,
                                   'filter_form': FilterForms,
                                   'template': 'list_move'}, name='list_move'),
    path('list_pat_part_two/', list_pat_part_two, name='list_pat_part_two'),
    # "Движение"->"Список больных"
    path('list_pat_view/', data_page, {'model': ListPatView, 'rec_form': ListPatViewForms,
                                       'filter_form': FilterForms,
                                       'template': 'list_pat_view'}, name='list_pat_view'),
    # "Внутренняя структура"->"Список отделений"
    path('internal_structure/', data_page, {'model': InternalStructure, 'rec_form': InternalStructureForms,
                                            'template': 'internal_structure'}, name='internal_structure'),
    path('treatment_result/', data_page, {'model': TreatmentResult, 'rec_form': TreatmentResultForms,
                                          'template': 'treatment_result'}, name='treatment_result'),
    path('medical_institution/', data_page, {'model': MedicalInstitution, 'rec_form': MedicalInstitutionForms,
                                             'template': 'medical_institution'}, name='medical_institution'),
    path('who_directed/', data_page, {'model': WhoDirected, 'rec_form': WhoDirectedForms, 'template': 'who_directed'},
         name='who_directed'),

    path('delivery_time/', data_page,
         {'model': DeliveryTime, 'rec_form': DeliveryTimeForms, 'template': 'delivery_time'},
         name='delivery_time'),

    path('autopsy/', data_page, {'model': Autopsy, 'rec_form': AutopsyForms, 'template': 'autopsy'}, name='autopsy'),
    path('group_operation/', data_page, {'model': GroupOperation, 'rec_form': GroupOperationForms,
                                         'template': 'group_operation'}, name='group_operation'),
]