import re

from pytest import mark, fixture, skip, param

from consts.stx import FlavorSpec
from consts.cli_errs import CpuAssignment   # DO not remove
from keywords import host_helper, system_helper, vm_helper, nova_helper, \
    check_helper, common
from testfixtures.fixture_resources import ResourceCleanup
from testfixtures.recover_hosts import HostsToRecover
from utils import table_parser
from utils.tis_log import LOG

def compare_cores_to_configure(host, func, p0, p1):
    """
    Compare current cores for given host/function and return whether to configure and numbers to configure

    Args:
        host (str):
        func (str):
        p0 (int):
        p1 (int):

    Returns (tuple): (bool, int, int)
        (<is_match>, <p0_to_config>, <p1_to_config>)

    """
    proc_core_dict = host_helper.get_host_cpu_cores_for_function(host, func=func, core_type='log_core')
    current_p0_num = len(proc_core_dict[0])
    current_p1_num = len(proc_core_dict[1])

    p0_to_config = None if p0 == current_p0_num else p0
    p1_to_config = None if p1 == current_p1_num else p1

    return p0_to_config is None and p1_to_config is None, p0_to_config, p1_to_config

@fixture(scope='class')
def check_avs_pattern():
    if not system_helper.is_avs():
        skip('VSwitch numa affinity unsupported by OVS')

@fixture(scope='module', autouse=True)
def host_to_config(request, add_admin_role_module, add_cgcsauto_zone):
    LOG.info("Looking for a host to reconfigure.")
    nova_hosts = host_helper.get_up_hypervisors()
    if len(nova_hosts) < 1:
        skip("No nova compute host available in the system, no host to lock and reconfigure.")

    storage_backing, hosts = host_helper.get_storage_backing_with_max_hosts()
    host = hosts[0]
    host_other = hosts[1] if len(hosts) > 1 else None

    if not host:
        skip("No nova host available to reconfigure in the system.")

    vswitch_proc_core_dict = host_helper.get_host_cpu_cores_for_function(host, func='vSwitch', core_type='log_core')
    pform_proc_core_dict = host_helper.get_host_cpu_cores_for_function(host, func='platform', core_type='log_core')

    proc1_exists = True if 1 in vswitch_proc_core_dict else False
    vswitch_original_num_p0 = len(vswitch_proc_core_dict[0])
    vswitch_original_num_p1 = len(vswitch_proc_core_dict[1]) if proc1_exists else None
    platform_ogigin_num_p0 = len(pform_proc_core_dict[0])

    def revert():
        post_vswitch_dict = host_helper.get_host_cpu_cores_for_function(host, func='vSwitch', core_type='log_core')
        post_pform_dict = host_helper.get_host_cpu_cores_for_function(host, func='platform', core_type='log_core')
        HostsToRecover.add(host, scope='module')

        LOG.fixture_step('(module) Revert host vswitch/platform cores if more than 2 cores per proc are assigned')
        if (vswitch_proc_core_dict != post_vswitch_dict or pform_proc_core_dict != post_pform_dict) and \
                (any([len(v) > 2 for v in post_vswitch_dict.values()]) or
                 any([len(v) > 2 for v in post_pform_dict.values()])):
            host_helper.lock_host(host, swact=True)
            host_helper.modify_host_cpu(host, 'vswitch', p0=vswitch_original_num_p0, p1=vswitch_original_num_p1)
            host_helper.modify_host_cpu(host, 'platform', p0=platform_ogigin_num_p0)
            host_helper.unlock_host(host, check_hypervisor_up=True)

    request.addfinalizer(revert)

    ht_enabled = host_helper.is_host_hyperthreaded(host)
    is_small_system = system_helper.is_aio_system()

    host_cpu_table = host_helper.get_host_cpu_list_table(host=host)
    proc_ids = sorted(list(set(table_parser.get_column(host_cpu_table, 'processor'))))

    LOG.info("{} is selected. Hyper-threading is {}enabled".format(host, "not " if ht_enabled else ""))
    return host, proc_ids, ht_enabled, is_small_system, host_other, storage_backing

def id_params_cores(val):
    if isinstance(val, tuple):
        return '_'.join([str(i) for i in val])

def _convert_ht_cpe_req(ht_req, cpe_req):
    if ht_req == 'HT':
        ht_req = True
    elif ht_req == 'nonHT':
        ht_req = False

    if cpe_req == 'AIO':
        cpe_req = True
    elif cpe_req == 'nonAIO':
        cpe_req = False

    return ht_req, cpe_req

class TestVSwitchCPUReconfig:

    @fixture(scope='class', autouse=True)
    def skip_for_vswitch_none(self):
        if system_helper.get_vswitch_type().lower() == 'none':
            skip('vswitch cpu config is not applicable to vswitch type - none')

    @fixture(scope='class')
    def flavor_(self, host_to_config):
        storage_backing = host_to_config[-1]
        flavor = nova_helper.create_flavor(name='flv_{}'.format(storage_backing),
                                           storage_backing=storage_backing)[1]
        ResourceCleanup.add('flavor', flavor, scope='class')

        return flavor

    @mark.trylast
    @mark.reboot
    @mark.p3
    @mark.parametrize(('platform', 'vswitch', 'ht_required', 'cpe_required'), [
        # (None, None, None, None),           # Test without reconfig
        # ((1, 0), (1, 1), None, 'nonAIO'),      # Standard lab only
        # ((2, 0), (1, 1), None, 'AIO'),       # CPE only
        ((1, 2), (3, 2), None, None),
        # ((1, 2), (2, 2), None, None),     # Unnecessary test
        # ((2, 0), (0, 0), None, None),  # Shared vswitch core feature,
        # which allows 0 dedicated vswitch core
        ((1, 0), (1, 0), 'nonHT', 'nonAIO'),  # Standard lab only
        ((2, 0), (1, 0), 'nonHT', 'AIO'),  # CPE only
        # ((2, 0), (2, 0), None, True),       # CPE only    # remove - covered by other test
        # ((1, 0), (2, 0), None, 'nonAIO'),      # Standard lab only
    ], ids=id_params_cores)
    def test_vswitch_cpu_reconfig_positive(self, host_to_config, flavor_, platform, vswitch,
                                           ht_required, cpe_required):
        """
        Test valid vswitch cpu reconfigurations, and verify vm can still be hosted on the modified host

        Args:
            host_to_config: hostname of the host to reconfig
            flavor_: fixture
            platform: cpu cores to config for platform
            vswitch: cpu cores to config for vswitch
            ht_required: whether hyperthreading is required for the testcase. skip test if requirement is not met
            cpe_required: whether cpe lab is required for the testcase. skip test if requirement is not met.

        Setups (module):
            - Find a nova host with minimum number of vms (or standby controller if CPE) for testing    (module)
            - Record the cpu configs for vswitch and platform   (module)

        Test Steps:
            - Lock host
            - Reconfigure host platform and vswitch cpus to give numbers
            - Unlock host
            - Check ports and vswitch cores mapping in vswitch.ini are correct
            - Check host is still eligible to schedule instance via in nova host-list
            - Boot a vm
            - Live migrate to host if it's not originally booted on host

        Teardown:
            - Revert host platform and vswitch cpu configs      (module)

        """
        host, proc_ids, ht_enabled, is_cpe, host_other, storage_backing = host_to_config
        HostsToRecover.add(host, scope='class')

        ht_required, cpe_required = _convert_ht_cpe_req(ht_required, cpe_required)
        if ht_required is not None and ht_required is not ht_enabled:
            skip("Hyper-threading for {} is not {}".format(host, ht_required))

        if cpe_required is not None and cpe_required is not is_cpe:
            skip("Small footprint is not {}".format(cpe_required))

        if platform is not None or vswitch is not None:
            LOG.tc_step("Reconfigure host cpus. Platform: {}, vSwitch: {}".format(platform, vswitch))
            platform_args = {}
            for i in range(len(proc_ids)):
                if platform[i] is not None:
                    platform_args['p' + str(i)] = platform[i]

            vswitch_args = {}
            for j in range(len(vswitch)):
                if j is not None:
                    vswitch_args['p' + str(j)] = vswitch[j]

            LOG.tc_step("Lock and modify cpu for {}".format(host))
            host_helper.lock_host(host, swact=True)
            if platform is not None:
                host_helper.modify_host_cpu(host, 'platform', **platform_args)
            if vswitch is not None:
                host_helper.modify_host_cpu(host, 'vswitch', **vswitch_args)
            host_helper.unlock_host(host, check_hypervisor_up=True)

        if system_helper.is_avs():
            LOG.tc_step("Check AVS ports and cores mapping are correct.")
            check_helper.check_host_vswitch_port_engine_map(host)

        LOG.tc_step("Check {} is still a valid nova host.".format(host))
        host_helper.wait_for_hypervisors_up(host)

        LOG.tc_step("Check vm can be launched on or live migrated to {}.".format(host))
        vm_id = vm_helper.boot_vm(flavor=flavor_, avail_zone='nova', vm_host=host, cleanup='function')[1]

        assert host == vm_helper.get_vm_host(vm_id), "VM is not booted on configured host"

    @fixture(scope='function')
    def check_alarms(self):
        pass

    @mark.trylast
    @mark.reboot
    @mark.parametrize(('platform', 'vswitch', 'ht_required', 'cpe_required', 'expt_err'), [
        param((2, 0), (5, 6), 'nonHT', None, "CpuAssignment.VSWITCH_TOO_MANY_CORES",
              marks=mark.p3),
        # Assume total<=10 cores/per proc & thread
        param((4, 0), (8, 10), None, None, "CpuAssignment.TOTAL_TOO_MANY_CORES", marks=mark.p3),
        # param((2, 0), (0, 0), None, None, "CpuAssignment.VSWITCH_INSUFFICIENT_CORES", marks=mark.p3), shared vswitch core feature
    ], ids=id_params_cores)
    def test_vswitch_cpu_reconfig_negative(self, host_to_config, platform, vswitch, ht_required, cpe_required,
                                           expt_err):
        """
        Test negative cases for setting vSwitch cores.
        Args:
            host_to_config:
            platform:
            vswitch:
            ht_required:
            cpe_required:
            expt_err:

        Setups:
            - Find a nova host with minimum number of vms (or standby controller if CPE) for testing    (module)
            - Record the cpu configs for vswitch and platform   (module)
        Test Steps
            - Lock host
            - Modify host cpu platform cores as specified
            - Attempt to modify host cpu vSwitch cores as specified
            - Verify cli is rejected with proper error message
        Teardown:
            - Revert host platform and vswitch cpu configs      (module)

        """
        host, proc_ids, ht_enabled, is_cpe, host_other, storage_backing = host_to_config

        if len(proc_ids) < 2:
            skip('Two processors are required for this test')

        HostsToRecover.add(host, scope='class')

        ht_required, cpe_required = _convert_ht_cpe_req(ht_required, cpe_required)

        if ht_required is not None and ht_required is not ht_enabled:
            skip("Hyper-threading for {} is not {}".format(host, ht_required))

        if cpe_required is not None and (cpe_required is not is_cpe):
            skip("Requires {} system.".format("non-CPE" if is_cpe else "CPE"))

        # FIXME
        # total_p0, total_p1 = host_helper.get_logcores_counts(host, proc_ids=(0, 1))
        total_p0, total_p1 = host_helper.get_logcores_counts(
            host, proc_ids=(0, 1), functions=['Application', 'vSwitch', 'Platform'])

        # convert test params if host to config has more than 10 cores per proc & threaad
        if 'NO_VM_CORE' in expt_err:
            # Unsure about expected behavior with Shared cores. FIXME
            # shared_p0, shared_p1 = host_helper.get_logcores_counts(host, proc_ids=(0, 1), functions='Shared')
            # if shared_p0 > 0 or shared_p1 > 0:
            #     skip("{} has shared core configured. Skip NO_VM_CORE semantic check".format(host))
            #
            platform = int(total_p0) - 2, int(total_p1) - 2
        elif 'TOTAL_TOO_MANY_CORES' in expt_err:
            if total_p0 > 10 and platform[0] + vswitch[0] > 10:
                diff = total_p0 - 10
                platform = platform[0] + diff, 0
            elif total_p1 > 10 and platform[1] + vswitch[1] > 10:
                diff = total_p1 - 10
                vswitch[1] += diff
        elif 'VSWITCH_TOO_MANY_CORES' in expt_err:
            if total_p0 > 10 and vswitch[0] + vswitch[1] > 10:
                diff = total_p0 - 10
                vswitch = vswitch[0] + diff, vswitch[1] + diff

        platform_args = {'p0': platform[0]}

        vswitch_args = {}
        for j in range(len(vswitch)):
            if j is not None:
                vswitch_args['p' + str(j)] = vswitch[j]

        # if is_cpe and system_helper.get_active_controller_name() == host:
        #     LOG.tc_step("{} is active controller, swact first".format(host))
        #     host_helper.swact_host(host)

        LOG.tc_step("Lock {}".format(host))
        host_helper.lock_host(host, swact=True)

        LOG.tc_step("Attempt to reconfigure host cpus. Platform: {}, vSwitch: {}".format(platform, vswitch))
        # host_helper.modify_host_cpu(host, 'vswitch', **{'p0': 1, 'p1': 0})
        host_helper.modify_host_cpu(host, 'platform', **platform_args)
        code, output = host_helper.modify_host_cpu(host, 'vswitch', fail_ok=True, **vswitch_args)

        LOG.tc_step("Verify modify host cpu vSwitch core request is rejected with expected error message.")
        assert 1 == code, "Modify host cpu request is not rejected."

        if "TOTAL_TOO_MANY_CORES" in expt_err:
            proc_id = 0 if platform[0] + vswitch[0] > total_p0 else 1
            expt_err = eval(expt_err).format(proc_id)
        elif "VSWITCH_INSUFFICIENT_CORES" in expt_err:
            min_core_num = 1  # 2 min platform cores for CPE
            expt_err = eval(expt_err).format(min_core_num)
        else:
            expt_err = eval(expt_err)

        assert expt_err in output, "Expected error string is not in output"

def _get_vms_cores_nums(host, vswitch_cores_dict):
    """

    Args:
        host (str): vm hostname

    Returns (tuple): number of cores for VMs function on non-vSwitch numa node, and vSwitch numa node

    """
    #  vswitch and non-vswitch nodes should be one each when this is called

    vms_cores_dict = host_helper.get_host_cpu_cores_for_function(host, func='Application')

    vswitch_procs = [proc for proc in vms_cores_dict if vswitch_cores_dict[proc]]
    nonvswitch_procs = [proc for proc in vms_cores_dict if not vswitch_cores_dict[proc]]

    vswitch_node_vm_cores = nonvswitch_node_vm_cores = 0
    if vswitch_procs:
        vswitch_node_vm_cores = len(vms_cores_dict[vswitch_procs[0]])
    if nonvswitch_procs:
        nonvswitch_node_vm_cores = len(vms_cores_dict[nonvswitch_procs[0]])

    return vswitch_node_vm_cores, nonvswitch_node_vm_cores

def _create_flavor(vcpus, storage_backing, vswitch_numa_affinity=None, numa_0=None, numa_nodes=None):
    LOG.tc_step("Create flavor with vcpus={}, vswitch_numa_affinity={}, numa_0={}, numa_nodes={}".
                format(vcpus, vswitch_numa_affinity, numa_0, numa_nodes))
    flv_id = nova_helper.create_flavor('numa_affinity', vcpus=vcpus, storage_backing=storage_backing)[1]
    ResourceCleanup.add('flavor', flv_id)

    specs = {FlavorSpec.CPU_POLICY: 'dedicated'}
    if numa_0 is not None:
        specs[FlavorSpec.NUMA_0] = numa_0
    if numa_nodes is not None:
        specs[FlavorSpec.NUMA_NODES] = numa_nodes
    if vswitch_numa_affinity is not None:
        specs[FlavorSpec.VSWITCH_NUMA_AFFINITY] = vswitch_numa_affinity
    nova_helper.set_flavor(flavor=flv_id, **specs)

    return flv_id

@fixture(scope='module')
def get_hosts(host_to_config):
    host0, proc_ids, ht_enabled, is_cpe, host1, storage_backing = host_to_config
    if not host1:
        storage_backing, hosts = host_helper.get_storage_backing_with_max_hosts()
        if len(hosts) < 2:
            skip("Less than two up hypervisors support same storage backing")
        else:
            host0 = hosts[0]
            host1 = hosts[1]

    LOG.fixture_step("(module) Delete all vms and volumes on the system")
    vm_helper.delete_vms(stop_first=False)

    LOG.fixture_step("(module) Update cores and instances quota for tenant to ensure vms can boot")
    vm_helper.set_quotas(cores=200, instances=20)

    hosts_to_conf = [host0, host1]
    LOG.fixture_step("(module) Add hosts to cgcsauto aggregate: {}".format(hosts_to_conf))
    nova_helper.add_hosts_to_aggregate('cgcsauto', hosts_to_conf)

    return host0, host1, storage_backing, ht_enabled

class TestNovaSchedulerAVS:

    @fixture(scope='class')
    def hosts_configured(self, check_avs_pattern, get_hosts, config_host_class):
        host0, host1, storage_backing, ht_enabled = get_hosts

        func = 'vSwitch'
        LOG.fixture_step("(class) Configure hosts to have 0 vSwitch cores on p0 and 2 vSwitch cores on p1: {}".
                         format((host0, host1)))

        def _mod_host(host__, p0, p1):
            host_helper.modify_host_cpu(host__, func, p0=p0, p1=p1)

        hosts_to_config = {}

        h0p0_is_match, h0p0_p0_to_conf, h0p0_p1_to_conf = compare_cores_to_configure(host0, func, p0=2, p1=0)
        if h0p0_is_match:
            p0_host = host0  # No config for host0
            p1_host = host1
            h1p1_is_match, h1p1_p0_to_conf, h1p1_p1_to_conf = compare_cores_to_configure(host1, func, p0=0, p1=2)
            if not h1p1_is_match:  # config host1
                hosts_to_config[p1_host] = {'p0': h1p1_p0_to_conf, 'p1': h1p1_p1_to_conf}

        else:
            h1p0_is_match, h1p0_p0_to_conf, h1p0_p1_to_conf = compare_cores_to_configure(host1, func, p0=2, p1=0)
            if h1p0_is_match:
                p0_host = host1
                p1_host = host0
                h0p1_is_match, h0p1_p0_to_conf, h0p1_p1_to_conf = compare_cores_to_configure(host0, func, p0=0,
                                                                                p1=2)
                if not h0p1_is_match:
                    hosts_to_config[p1_host] = {'p0': h0p1_p0_to_conf, 'p1': h0p1_p1_to_conf}
            else:
                h1p1_is_match, h1p1_p0_to_conf, h1p1_p1_to_conf = compare_cores_to_configure(host1, func, p0=0,
                                                                                p1=2)
                if h1p1_is_match:
                    p1_host = host1
                    p0_host = host0
                    hosts_to_config[p0_host] = {'p0': h0p0_p0_to_conf, 'p1': h0p0_p1_to_conf}
                    # hosts_to_config[p1_host] = {'p0': h1p1_p0_to_conf, 'p1': h1p1_p1_to_conf}
                else:
                    # no match for (2,0) for both hosts, and host1 don't match (0,2) either - configure host1 to (2,0)
                    p0_host = host1
                    hosts_to_config[p0_host] = {'p0': h1p0_p0_to_conf, 'p1': h1p0_p1_to_conf}
                    p1_host = host0
                    h0p1_is_match, h0p1_p0_to_conf, h0p1_p1_to_conf = compare_cores_to_configure(host0, func, p0=0,
                                                                                p1=2)
                    if not h0p1_is_match:
                        hosts_to_config[p1_host] = {'p0': h0p1_p0_to_conf, 'p1': h0p1_p1_to_conf}

        assert p1_host and p0_host, "Check automation code. Init host should have been assigned"

        for host_, configs in hosts_to_config.items():
            config_host_class(host_, _mod_host, **configs)

        is_match_p0 = compare_cores_to_configure(p0_host, func, p0=2, p1=0)[0]
        is_match_p1 = compare_cores_to_configure(p1_host, func, p0=0, p1=2)[0]
        assert is_match_p0, "{} does not match vswitch core (2, 0)".format(p0_host)
        assert is_match_p1, "{} does not match vswitch core (0, 2)".format(p1_host)

        final_hosts_configured = [p1_host, p0_host]

        return final_hosts_configured, storage_backing, ht_enabled

    # Deprecated - numa pinning. vswitch affinity is covered by test_vswitch_numa_affinity_sched_vms_two_hosts_avail
    @mark.parametrize(('vswitch_numa_affinity', 'numa_0', 'numa_nodes', 'expt_err'), [
        ('strict', 0, None, "NumaErr.NUMA_VSWITCH_MISMATCH"),  # This error message has inconsistent formatting
        ('prefer', 0, None, None),
        ('strict', None, 1, None),
        ('prefer', None, None, None),
        ('strict', None, 2, 'NumaErr.TWO_NUMA_ONE_VSWITCH')  # This error message is confusing
    ])
    def _test_vswitch_numa_affinity_boot_vm(self, hosts_configured, vswitch_numa_affinity, numa_0,
                                            numa_nodes, expt_err):
        """

        Args:
            hosts_configured (tuple): fixture to configure two hosts
            vswitch_numa_affinity (str):
            numa_0 (int):
            numa_nodes (int):
            expt_err (str):

        Setups:
            - Add admin role to primary tenant
            - Create cgcsauto aggregate
            - Delete all vms on the system
            - Configure a host with vswitch = 0, 2, and another with vswitch = 2, 0 and add them to cgcsauto zone

        Test Steps:
            - Create flavor with 2 dedicated vcpus, and specified vswitch numa affinity, numa_0 and numa_nodes
            - Boot vm with above flavor
                - Check vm is booted successfully on expected numa node and host
                - or failed with proper error message in nova show

        """
        hosts_configured, storage_backing, ht_enabled = hosts_configured
        expt_host = hosts_configured[0]
        expt_numa = 1 if numa_0 is None else numa_0

        flv_id = _create_flavor(2, storage_backing, vswitch_numa_affinity, numa_0, numa_nodes)

        LOG.tc_step("Boot vm from volume using above flavor")
        code, vm_id, err = vm_helper.boot_vm('numa_affinity', flavor=flv_id, cleanup='function',
                                             avail_zone='cgcsauto', vm_host=expt_host, fail_ok=True)

        if expt_err:
            LOG.tc_step("Check boot vm failed due to conflict in vswitch node affinity and numa nodes requirements")
            assert 1 == code, "Boot vm is not rejected with conflicting requirements"
            actual_err = vm_helper.get_vm_fault_message(vm_id)
            expt_err = eval(expt_err).format(0)

            assert re.search(expt_err, actual_err), "Expected fault message is not found from nova show"
        else:
            LOG.tc_step("Check vm is booted successfully on numa node {}".format(expt_numa))
            assert 0 == code, "Boot vm is not successful. Details: {}".format(err)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
            assert expt_host == vm_host, "VM {} is not booted on expected host".format(vm_id)
            assert expt_numa == vm_numa[0], "VM {} is booted on numa{} instead of numa{}".format(vm_id, vm_numa[0],
                                                                                expt_numa)

    @fixture(scope='class')
    def cal_vm_cores_two_hosts(self, hosts_configured):
        hosts_configured, storage_backing, ht_enabled = hosts_configured

        LOG.fixture_step("(class) Calculate the vcpus for flavor when two hosts available to schedule vms")
        total_vswitch_vm_cores = 0
        hosts_vswitch_vm_cores = []
        min_vm_cores = 200
        final_host = None
        hosts_vswitch_proc = {
            hosts_configured[0]: 1,
            hosts_configured[1]: 0,
        }
        for host in hosts_configured:
            vms_cores_dict = host_helper.get_host_cpu_cores_for_function(host, func='Application')
            vswitch_vm_cores = len(vms_cores_dict[hosts_vswitch_proc[host]])
            if host_helper.is_host_hyperthreaded(host):
                vswitch_vm_cores *= 2
            hosts_vswitch_vm_cores.append(vswitch_vm_cores)
            total_vswitch_vm_cores += vswitch_vm_cores

            if vswitch_vm_cores < min_vm_cores:
                min_vm_cores = vswitch_vm_cores
                final_host = host

        hosts_configured = list(hosts_configured)
        hosts_configured.remove(final_host)
        other_host = hosts_configured[0]
        flavor_vcpu_num = int(total_vswitch_vm_cores / 7) + 1

        vms_num = 0
        for vm_cores in hosts_vswitch_vm_cores:
            vms_num += int(vm_cores / flavor_vcpu_num)

        return final_host, other_host, hosts_vswitch_proc, flavor_vcpu_num, vms_num, storage_backing

    @mark.parametrize('vswitch_numa_affinity', [
        'strict',
        'prefer',
        None,
    ])
    def _test_vswitch_numa_affinity_sched_vms_two_hosts_avail(self, cal_vm_cores_two_hosts, vswitch_numa_affinity):
        """

        Args:
            cal_vm_cores_two_hosts (tuple): fixture to calculate flavor vcpu number
            vswitch_numa_affinity (str):

        Setups:
            - Add admin role to primary tenant
            - Create cgcsauto aggregate
            - Delete all vms on the system
            - Select a host with vswitch = 0, 2, and antother with vswitch = 2, 0 and add them to cgcsauto zone
            - Select the host with less vm cores on vswitch node as target_host
            - Calculate favor vcpu number so that max 6 vms can be booted vswitch nodes

        Test Steps;
            - Create a flavor with calculated vcpu number and specified vswitch numa affinity
            - Boot vms with above flavor until vswitch nodes on both computes are full
            - Check above vms are booted on vswitch nodes of selected hosts
            - Attempt to boot one more vm
                - Check it failed if vswitch numa affinity = strict
                - Check it booted on non-vswitch node if vswitch numa affinity = prefer
            - Delete all vms on host_other
            - Cold migrate vms away from target_host and ensure they are moved to vswitch node of host_other
            - Live migrate vms from other host, and ensure they are moved to vswitch ndoe of target host
            - Reboot vms host and ensure vms are evacuated to host_other

        Teardown:
            - Delete created vms, flavors, volumes
            - Remove hosts from cgcsauto aggregate
            - Delete cgcsauto aggregate
            - Remove admin role from tenanat

        """
        final_host, other_host, hosts_vswitch_numa, flavor_vcpu_num, vms_num, storage_backing = cal_vm_cores_two_hosts
        expt_hosts = [final_host, other_host]

        flv_id = _create_flavor(flavor_vcpu_num, storage_backing, vswitch_numa_affinity)

        LOG.tc_step("Boot {} VMs and ensure they are booted on vswitch numa node".format(vms_num))
        final_host_vms = []
        total_cpus = {final_host: 0, other_host: 0}
        for i in range(vms_num):
            code, vm_id, err = vm_helper.boot_vm('vswitch_numa', flavor=flv_id, cleanup='function',
                                                      avail_zone='cgcsauto', fail_ok=True)

            assert 0 == code, "VM is not booted successfully. Details: {}".format(err)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
            vm_numa = vm_numa[0]
            assert vm_host in expt_hosts, "VM is not booted on cgcsauto hosts"

            expt_numa = hosts_vswitch_numa[vm_host]

            # CGTS-6389: vswitch engine availability is not considered in host selection for prefer
            if vswitch_numa_affinity != 'strict':
                if expt_numa != vm_numa:
                    LOG.warning("VM{} - {} is not booted on expected host. Applying workaround.".format(i, vm_id))
                    vm_helper.live_migrate_vm(vm_id)
                    vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
                    vm_numa = vm_numa[0]
                    expt_numa = hosts_vswitch_numa[vm_host]

            assert expt_numa == vm_numa, "VM {} is not booted on vSwitch node of {}".format(vm_id, vm_host)

            if vm_host == final_host:
                final_host_vms.append(vm_id)

            total_cpus[vm_host] += flavor_vcpu_num
            expt_total = total_cpus[vm_host]
            LOG.tc_step("Check total allocated vcpus is {} from nova-compute.log on {}".format(expt_total, other_host))
            host_helper.wait_for_total_allocated_vcpus_update_in_log(vm_host, expt_cpus=expt_total, fail_ok=False)

        # Now vswitch nodes on both hosts are full. Attempt to boot another VM
        extra_str = 'rejected' if vswitch_numa_affinity == 'strict' else ' booted on non-vSwitch node - proc_0'
        LOG.tc_step("vSwitch nodes are full. Attempt to boot one more vm and ensure it's {}".format(extra_str))
        code, vm_id, err = vm_helper.boot_vm('vswitch_numa', flavor=flv_id, cleanup='function',
                                             avail_zone='cgcsauto', vm_host=final_host, fail_ok=True)

        if vswitch_numa_affinity == 'strict':
            assert 1 == code, "VM boot is not rejected even though vSwitch node is full. Details: {}".format(err)
        else:
            assert 0 == code, "VM is not booted successfully on another node. Details: {}".format(err)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
            vm_numa = vm_numa[0]
            assert vm_host in expt_hosts, "VM is not booted on cgcsauto hosts"
            assert hosts_vswitch_numa[vm_host] != vm_numa, "VM is not booted on non-vSwitch node"

            if vm_host != final_host:
                vm_helper.live_migrate_vm(vm_id, final_host)

            # Add the vm to the first so we can verify a prefer vm that was on non-vSwitch node will be migrated to
            # vSwitch ndoe when sufficient vm cores available on other host
            final_host_vms.insert(0, vm_id)

        if vswitch_numa_affinity is not None:
            # Test vm actions for prefer and strict. None should be the same as prefer, so skip it for None.
            LOG.tc_step("Delete all vms on {}".format(other_host))
            vms_to_del = vm_helper.get_vms_on_host(other_host)
            vm_helper.delete_vms(vms_to_del)
            LOG.tc_step("Check total allocated vcpus is 0 from nova-compute.log on {}".format(other_host))
            host_helper.wait_for_total_allocated_vcpus_update_in_log(other_host, expt_cpus=0, fail_ok=False)

            vswitch_vm_num = len(final_host_vms) if vswitch_numa_affinity == 'strict' else (len(final_host_vms) - 1)

            for action in ('cold_migrate', 'live_migrate'):
                LOG.tc_step("{} {} VMs and ensure they are migrated to vswitch node of other host".
                            format(action, vswitch_vm_num))
                for i in range(vswitch_vm_num):
                    vm_ = final_host_vms[i]
                    code, output = vm_helper.perform_action_on_vm(vm_, action=action, fail_ok=True)
                    assert 0 == code, "{}    vm{} unsuccessful. Details: {}".format(action, i, output)
                    vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_)
                    vm_numa = vm_numa[0]
                    assert hosts_vswitch_numa[vm_host] == vm_numa, "VM{} is not {}d to vswitch node".format(i, action)

                if vswitch_numa_affinity != 'strict':
                    last_vm = final_host_vms[-1]
                    LOG.tc_step("{} last vm to other host and ensure it succeeded".format(action))
                    code, output = vm_helper.perform_action_on_vm(last_vm, action=action)
                    assert 0 == code, "{} vm unsuccessful. Details: {}".format(action, output)
                    vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(last_vm)
                    vm_numa = vm_numa[0]
                    if vm_host == other_host and vswitch_vm_num < vms_num / 2:
                        assert hosts_vswitch_numa[vm_host] == vm_numa, "Last VM is not {}d to vSwitch node of {}". \
                            format(action, vm_host)
                    else:
                        assert hosts_vswitch_numa[vm_host] != vm_numa, "Last VM is not {}d to non-vSwitch node of {}". \
                            format(action, vm_host)

            LOG.tc_step("Reboot {} and ensure vms are evacuated successfully".format(final_host))
            vm_helper.evacuate_vms(final_host, final_host_vms)

    @fixture(scope='class')
    def cal_vm_cores_one_host(self, hosts_configured):
        hosts_configured, storage_backing, ht_enabled = hosts_configured

        LOG.fixture_step("(class) Determine host to boot vms on and calculate the vcpus for flavor")

        initial_host, other_host = hosts_configured
        vms_cores_dict = host_helper.get_host_cpu_cores_for_function(initial_host, func='Application')
        p1_vm_cores = len(vms_cores_dict[1])
        # p0_vm_cores = len(vms_cores_dict[0])
        if host_helper.is_host_hyperthreaded(initial_host):
            p1_vm_cores *= 2
            # p0_vm_cores *= 2

        if p1_vm_cores > 15:
            vm_count = 3
        else:
            vm_count = 2
        flavor_vcpu_num = int(p1_vm_cores / (vm_count + 1)) + 1

        return initial_host, other_host, flavor_vcpu_num, storage_backing, vm_count

    # Deprecated. virtual numa pinning + vswitch affinity restricted the vm to be on one host. numa pinning is removed.
    def _test_vswitch_numa_affinity_sched_vms_one_host_avail(self, cal_vm_cores_one_host):
        """
        Test vswitch numa affinity strict when numa_0.0 = 1 which limits the vm host to only 1 host

        Args:
            cal_vm_cores_one_host (tuple): fixture to get host with vswitch node on proc1 and calculate flavor vcpu num

        Setups:
            - Add admin role to primary tenant
            - Create cgcsauto aggregate
            - Delete all vms on the system
            - Select a target host vswitch = 0, 2, and host_other vswitch = 2, 0 and add them to cgcsauto zone

        Test Steps;
            - Create a flavor with vswitch_numa_affinity=strict and vcpu_num = int(p1_vm_cores/4)+1 so that max 3
                vms can be booted on vswitch node (or max 2 vms if p1_vm_cores < 15)
            - Boot vms with above flavor until vswitch node full
            - Check above vms are booted on expected host and numa node
            - Attempt to boot one more vm and ensure it failed
            - Attempt to live and cold migrate active vms, and ensure they are rejected
            - Reboot vm host and ensure vm stays on same host and return active after host is back up

        Teardown:
            - Delete created vms, flavors, volumes
            - Remove hosts from cgcsauto aggregate
            - Delete cgcsauto aggregate
            - Remove admin role from tenanat

        """
        expt_host, other_host, flavor_vcpu_num, storage_backing, vm_count = cal_vm_cores_one_host

        flv_id = _create_flavor(flavor_vcpu_num, storage_backing, 'strict', 1)

        LOG.tc_step("Boot 3 VMs and ensure they are booted on vswitch numa node on {}".format(expt_host))
        vms = []
        for i in range(vm_count):
            code, vm_id, err = vm_helper.boot_vm('vswitch_numa_one_host', flavor=flv_id, cleanup='function',
                                                 avail_zone='cgcsauto', fail_ok=True)
            assert 0 == code, "VM is not booted successfully. Details: {}".format(err)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
            vm_numa = vm_numa[0]
            assert expt_host == vm_host, "VM is booted on {} instead of {}".format(vm_host, expt_host)
            assert 1 == vm_numa, "VM is not booted on vSwitch node: proc_1"

            vms.append(vm_id)

        LOG.tc_step("Boot one more vm and ensure it's rejected")
        code, vm_id, err = vm_helper.boot_vm('vswitch_numa', flavor=flv_id, cleanup='function',
                                             avail_zone='cgcsauto', fail_ok=True)
        assert 1 == code, "VM boot is not rejected even though vSwitch node is full. Details: {}".format(err)

        LOG.tc_step("Attempt to live/cold migrate booted vms and ensure it's rejected")
        for vm_ in vms:
            for action in ('live_migrate', 'cold_migrate'):
                code, output = vm_helper.perform_action_on_vm(vm_, action=action, fail_ok=True)
                assert 2 == code, "{} is not rejected. Details: {}".format(action, output)

                vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_)
                vm_numa = vm_numa[0]
                assert expt_host == vm_host
                assert 1 == vm_numa

        LOG.tc_step("Reboot vm host and ensure vms stayed on same host")
        code, err_vms = vm_helper.evacuate_vms(expt_host, vms, wait_for_host_up=True, timeout=300, fail_ok=True)
        assert 1 == code, "Reboot host with vms are not as expected."
        assert sorted(err_vms) == sorted(vms), "Not all vms stayed on expected host"

        LOG.tc_step("Ensure vms are active after host recovers")
        vm_helper.wait_for_vms_values(vms=vms, timeout=300, fail_ok=False)

    @fixture(scope='class')
    def get_target_host_and_flavors(self, hosts_configured, request):
        hosts, storage_backing, ht_enabled = hosts_configured
        other_host, target_host = hosts
        ht_enabled = host_helper.is_host_hyperthreaded(target_host)
        LOG.fixture_step("(class) Add {} to cgcsauto aggregate".format(target_host))
        nova_helper.add_hosts_to_aggregate('cgcsauto', target_host)

        def _add_other_host():
            LOG.fixture_step("(class) Add {} to cgcsauto aggregate".format(other_host))
            nova_helper.add_hosts_to_aggregate('cgcsauto', other_host)

        request.addfinalizer(_add_other_host)

        LOG.fixture_step("(class) Remove {} from cgcsauto aggregate".format(other_host))
        nova_helper.remove_hosts_from_aggregate('cgcsauto', other_host)

        LOG.fixture_step("(class) Check vswitch numa node on {} doesn't have the most vm cores.".format(target_host))
        vswitch_cores_dict = host_helper.get_host_cpu_cores_for_function(target_host, func='vSwitch')
        vswitch_vm_cores_num, nonvswitch_vm_cores_num = _get_vms_cores_nums(target_host, vswitch_cores_dict)
        assert nonvswitch_vm_cores_num > vswitch_vm_cores_num, "vSwitch numa node has the most vm cores."

        if ht_enabled:
            vswitch_vm_cores_num *= 2
            nonvswitch_vm_cores_num *= 2
        vswitch_proc = list(vswitch_cores_dict.keys())[0]

        LOG.fixture_step("(class) Create a origin flavor with 2 vcpus and boot a vm with this flavor.")
        pre_flavor = nova_helper.create_flavor(name='2_vcpus', vcpus=2)[1]
        ResourceCleanup.add('flavor', resource_id=pre_flavor, scope='class')
        nova_helper.set_flavor(pre_flavor, **{FlavorSpec.CPU_POLICY: 'dedicated'})

        LOG.fixture_step("(class) Create dest flavor with vcpu number larger than the available cores on "
                         "current numa node")
        huge_flavor = nova_helper.create_flavor(name='many_vcpus', vcpus=vswitch_vm_cores_num + 1)[1]
        ResourceCleanup.add('flavor', huge_flavor, scope='class')
        nova_helper.set_flavor(huge_flavor, **{FlavorSpec.CPU_POLICY: 'dedicated'})

        return target_host, vswitch_proc, vswitch_vm_cores_num, nonvswitch_vm_cores_num, pre_flavor, huge_flavor

    @mark.parametrize(('vswitch_numa_affinity', 'resize_revert'), [
        param('strict', 'confirm', marks=mark.p3),
        param('prefer', 'confirm', marks=mark.p3),
        param('prefer', 'revert', marks=mark.p3)
    ])
    def _test_vswitch_affinity_resize_insufficient_cores_on_vswitch_node(self, get_target_host_and_flavors,
                                                                         vswitch_numa_affinity, resize_revert):
        """
        Test vswitch numa affinity when attempt to resize with insufficient cores on vswitch node
        Args:
            get_target_host_and_flavors (tuple): fixture to get target_host and flavor with large vcpu number
            vswitch_numa_affinity (str):
            resize_revert (str):

        Setups:
            - Add admin role to primary tenant
            - Create cgcsauto aggregate
            - Delete all vms on the system
            - Select target host with vswitch = 2, 0 and add it to cgcsauto aggregate
            - Create a flavor with 2 vcpus and vswitch affinity
            - Create another flavor with many vcpus = vswitch node vm cores + 1

        Test Steps;
            - Boot a vm with dedicated 2 vcpu flavor in cgcsauto zone
            - Check vm is booted on cgcsauto host
            - Set vswitch numa affinity as specified on huge vcpu flavor
            - Attempt to resize to huge flavor
            - Check resize only succeeds if vswitch numa affinity = prefer

        Teardown:
            - Delete created vms, flavors, volumes
            - Remove hosts from cgcsauto aggregate
            - Delete cgcsauto aggregate
            - Remove admin role from tenanat

        """
        resize_revert = False if resize_revert == 'confirm' else True
        target_host, vswitch_proc, vswitch_vm_cores_num, nonvswitch_vm_cores_num, pre_flavor, huge_flavor = \
            get_target_host_and_flavors

        LOG.tc_step("Boot a vm with origin flavor with 2 vcpus")
        vm_id = vm_helper.boot_vm(flavor=pre_flavor, avail_zone='cgcsauto', cleanup='function')[1]

        LOG.tc_step("Check vm is booted on same numa node with vSwitch of {} via vm-topology".format(target_host))
        pre_vm_host, pre_numa_nodes = vm_helper.get_vm_host_and_numa_nodes(vm_id)
        assert target_host == pre_vm_host, "VM host is not host under test"
        assert vswitch_proc == pre_numa_nodes[0], "VM {} is not booted on vswitch numa node {}". \
            format(vm_id, vswitch_proc)

        nova_helper.set_flavor(huge_flavor, **{FlavorSpec.VSWITCH_NUMA_AFFINITY: vswitch_numa_affinity})
        LOG.tc_step("Resize {}vm to above huge flavor with vswitch numa affinity {}".
                    format('and revert ' if resize_revert else '', vswitch_numa_affinity))

        code, output = vm_helper.resize_vm(vm_id, flavor_id=huge_flavor, revert=resize_revert, fail_ok=True)

        LOG.tc_step("Check vm is on same host")
        post_vm_host, post_numa_nodes = vm_helper.get_vm_host_and_numa_nodes(vm_id)
        assert target_host == post_vm_host, "VM is no longer on same host"

        if vswitch_numa_affinity == 'strict':
            LOG.tc_step("Check vm resize request is rejected with AVS strict due to insufficient cores on vSwitch node")
            assert 1 == code, "Resize with strict AVS policy is not rejected. Details: {}".format(output)
            assert vswitch_proc == post_numa_nodes[0], "VM is moved to non-vSwitch numa node even if resize is rejected"
        else:
            LOG.tc_step("Check resize succeeded with AVS perfer")
            assert 0 == code, "Resize with prefer AVS policy is not successful. Details: {}".format(output)
            if resize_revert:
                LOG.tc_step("Resize reverted - check vm remains on vswitch numa node on {}".format(target_host))
                assert vswitch_proc == post_numa_nodes[0], "VM is moved to non-vSwitch numa node after revert"
            else:
                LOG.tc_step("Resized to huge flavor - check vm is resized to non-vswitch numa node on same host")
                assert vswitch_proc != post_numa_nodes[0], "VM did not move to non-vSwitch numa node"

# Deprecated. numa pinning is removed. VM cannot be on two numa nodes.
class TestSpanNumaNodes:
    @fixture(scope='class')
    def span_numa_hosts(self, check_avs_pattern, get_hosts, config_host_class):
        host0, host1, storage_backing, ht_enabled = get_hosts

        function = 'vSwitch'
        LOG.fixture_step("(class) Configure hosts to have 0 vSwitch cores on p0 and 2 vSwitch cores on p1: {}")

        def _mod_host(host_, p0, p1):
            kwargs = {}
            if p0 is not None:
                kwargs['p0'] = p0
            if p1 is not None:
                kwargs['p1'] = p1

            host_helper.modify_host_cpu(host_, function, **kwargs)

        is_match, p0_to_conf, p1_to_conf = compare_cores_to_configure(host0, function, p0=2, p1=0)
        if is_match:
            host_span = host1
            host_other = host0
        else:
            host_span = host0
            host_other = host1
            is_match_other, p0_to_conf_other, p1_to_conf_other = compare_cores_to_configure(host1, function, p0=2, p1=0)
            if not is_match_other:
                LOG.fixture_step("Config {} vswitch cores to 2,0".format(host_other))
                config_host_class(host_span, _mod_host, **{'p0': p0_to_conf_other, 'p1': p1_to_conf_other})

        is_match_span, p0_to_conf_span, p1_to_conf_span = compare_cores_to_configure(host_span, function, p0=2, p1=2)
        if not is_match_span:
            LOG.fixture_step("Config {} vswitch cores to 2,2".format(host_span))
            config_host_class(host_span, _mod_host, **{'p0': p0_to_conf_span, 'p1': p1_to_conf_span})

        ht_enabled = host_helper.is_host_hyperthreaded(host_span)
        return host_span, host_other, storage_backing, ht_enabled

    @staticmethod
    def create_flavor_span_numa(vcpus, vswitch_affinity, storage_backing, numa0, numa0_cpus, numa0_mem, numa1,
                                numa1_cpus, numa1_mem):

        LOG.tc_step("Create a 1024ram flavor with specified vcpus")
        name = 'vswitch_affinity_{}_1G_{}cpu'.format(vswitch_affinity, vcpus)
        flv_id = nova_helper.create_flavor(name=name, vcpus=vcpus, ram=1024, storage_backing=storage_backing)[1]
        ResourceCleanup.add('flavor', flv_id)

        specs = {FlavorSpec.CPU_POLICY: 'dedicated', FlavorSpec.NUMA_NODES: 2,
                 FlavorSpec.VSWITCH_NUMA_AFFINITY: vswitch_affinity}
        tmp_dict = {FlavorSpec.NUMA_0: numa0,
                    FlavorSpec.NUMA0_CPUS: numa0_cpus,
                    FlavorSpec.NUMA0_MEM: numa0_mem,
                    FlavorSpec.NUMA_1: numa1,
                    FlavorSpec.NUMA1_CPUS: numa1_cpus,
                    FlavorSpec.NUMA1_MEM: numa1_mem}

        for key, val in tmp_dict.items():
            if val is not None:
                specs[key] = val

        LOG.tc_step("Add following extra spec to flavor {}: {}".format(flv_id, specs))
        nova_helper.set_flavor(flv_id, **specs)

        return flv_id

    @fixture(scope='class')
    def base_flavor_span_numa(self, span_numa_hosts):
        host_span, host_other, storage_backing, ht_enabled = span_numa_hosts
        LOG.fixture_step("(class) Create a 1024ram flavor with specified vcpus")
        flv_id = nova_helper.create_flavor(name='vswitch_affinity_strict_2vcpu', vcpus=4, ram=1024,
                                           storage_backing=storage_backing)[1]
        ResourceCleanup.add('flavor', flv_id, scope='class')

        specs = {FlavorSpec.CPU_POLICY: 'dedicated', FlavorSpec.NUMA_NODES: 2,
                 FlavorSpec.VSWITCH_NUMA_AFFINITY: 'strict',
                 FlavorSpec.NUMA_0: 1,
                 FlavorSpec.NUMA_1: 0
                 }

        LOG.fixture_step("(class) Add following extra spec to flavor {}: {}".format(flv_id, specs))
        nova_helper.set_flavor(flv_id, **specs)

        return flv_id

    @staticmethod
    def expt_vcpu_num_on_numa(vcpus, numa0_cpus, numa1_cpus):
        tmp_dict = {
            0: numa0_cpus,
            1: numa1_cpus
        }
        default_num = int(vcpus / 2)
        vcpu_on_numa = {}
        for key, val in tmp_dict.items():
            if val is None:
                num = default_num
            else:
                num = len(str(val).split(','))
            vcpu_on_numa[key] = num

        return vcpu_on_numa

    @mark.parametrize((
            'vcpus', 'vswitch_affinity', 'numa0', 'numa0_cpus', 'numa0_mem', 'numa1', 'numa1_cpus', 'numa1_mem'), [
        (3, 'strict', 0, 0, 512, 1, '1,2', 512),
        (2, 'strict', None, 0, 512, None, 1, 512),
        # (2, 'prefer', None, None, None, None, None, None),
        # (3, 'prefer', 0, None, None, 1, None, None, 'NumaErr.UNDEVISIBLE')
    ])
    def _test_vm_actions_vswitch_span_numa_nodes(self, span_numa_hosts, vcpus, vswitch_affinity, numa0, numa0_cpus,
                                                 numa0_mem, numa1, numa1_cpus, numa1_mem, base_flavor_span_numa):
        """
        Test nova actions on 2 numa nodes vm with vswitch numa affinity set

        Args:
            span_numa_hosts(tuple): fixture to config hosts
            vcpus (int):
            vswitch_affinity (str):
            numa0 (int):
            numa0_cpus (int|str):
            numa0_mem (int):
            numa1 (int):
            numa1_cpus (int|str):
            numa1_mem (int):
            base_flavor_span_numa (str): fixture returns 4 vcpu 2 numa nodes flavor to resize to

        Setups:
            - Add admin role to primary tenant
            - Create cgcsauto aggregate
            - Select two hypervisors with same storage backing and add them to cgcsauto aggregate
            - Delete all vms on the system
            - Config host so that 1 host_other vswitch = 2, 0 and host_span vswitch = 2, 2

        Test Steps;
            - Create flavor with 2 numa nodes and given test func parameters
            - Boot vm using above flavor in cgcsauto zone
            - Check vm is booted on host_span and span on both numa nodes
            - Check vm topology is as specified
            - Attempt to live and cold migrate vm and ensure it's rejected
            - Resize revert to 4vcpu and 2numa nodes flavor
            - Check vm stays on same host and topology stays the same
            - Resize confirm to 4vcpu and 2numa nodes flavor
            - Check vm stays on same host and topology updated

        Teardown:
            - Delete created vms, flavors, volumes
            - Remove hosts from cgcsauto aggregate
            - Delete cgcsauto aggregate
            - Remove admin role from tenanat

        """
        host_span, host_other, storage_backing, ht_enabled = span_numa_hosts

        flavor = self.create_flavor_span_numa(vcpus, vswitch_affinity, storage_backing, numa0, numa0_cpus, numa0_mem,
                                              numa1, numa1_cpus, numa1_mem)

        LOG.tc_step("Boot a vm with above flavor")
        code, vm_id, err = vm_helper.boot_vm('span_numa_{}'.format(vswitch_affinity), cleanup='function',
                                        flavor=flavor, fail_ok=True, avail_zone='cgcsauto')

        expt_numa0 = numa0 if numa0 is not None else 0
        expt_numa1 = numa1 if numa1 is not None else 1
        expt_numas = [expt_numa0, expt_numa1]

        LOG.tc_step("Check vm is booted successfully and span on both numa node")
        assert 0 == code, "Boot vm is not successful. Details: {}".format(err)
        vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
        assert host_span == vm_host, "VM {} is not booted on expected host".format(vm_id)
        assert expt_numas == vm_numa, "VM {} is booted on numa-{} instead of [0,1]".format(vm_id, vm_numa)

        LOG.tc_step("Check vm topology after vm boot")
        expt_vcpu_on_numa = self.expt_vcpu_num_on_numa(vcpus=vcpus, numa0_cpus=numa0_cpus, numa1_cpus=numa1_cpus)
        check_helper._check_vm_topology_via_vm_topology(vm_id, vcpus, 'dedicated', cpu_thr_pol=None, numa_num=2,
                                                        vm_host=vm_host, is_ht=ht_enabled,
                                                        vcpus_on_numa=expt_vcpu_on_numa)

        for action in ('live_migrate', 'cold_migrate'):
            code, output = vm_helper.perform_action_on_vm(vm_id, action=action, fail_ok=True)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)

            if vswitch_affinity == 'strict':
                assert 1 == code, "{} is not rejected. Details: {}".format(action, output)
                assert host_span == vm_host
            else:
                assert 0 == code, "VM is not {}d successfully even though vswitch affinity is prefer".format(action)

            assert expt_numas == vm_numa

        assert host_span == vm_host

        LOG.tc_step("Check vm topology did not change after migration reject")
        check_helper._check_vm_topology_via_vm_topology(vm_id, vcpus, 'dedicated', cpu_thr_pol=None, numa_num=2,
                                                        vm_host=vm_host, is_ht=ht_enabled,
                                                        vcpus_on_numa=expt_vcpu_on_numa)

        for revert in (True, False):
            extra_str = 'revert' if revert else 'confirm'
            expt_vcpu = vcpus if revert else 4
            expt_numa0_cpus = numa0_cpus if revert else None
            expt_numa1_cpus = numa1_cpus if revert else None
            expt_vm_numa = expt_numas if revert else [1, 0]

            LOG.tc_step("Resize {} to a 2-numa 4-vcpu flavor - ensure vm stays on same host and "
                        "span on two numa nodes".format(extra_str))
            vm_helper.resize_vm(vm_id, flavor_id=base_flavor_span_numa, revert=revert)
            vm_host, vm_numa = vm_helper.get_vm_host_and_numa_nodes(vm_id)
            assert host_span == vm_host, "VM host changed after resize {}".format(extra_str)
            assert expt_vm_numa == vm_numa, "Unexpected VM numa nodes after resize {}".format(extra_str)

            LOG.tc_step("Check vm topology after resize {}".format(extra_str))
            post_vcpu_on_numa = self.expt_vcpu_num_on_numa(vcpus=expt_vcpu, numa0_cpus=expt_numa0_cpus,
                                                           numa1_cpus=expt_numa1_cpus)
            check_helper._check_vm_topology_via_vm_topology(vm_id, expt_vcpu, 'dedicated', cpu_thr_pol=None, numa_num=2,
                                                            vm_host=vm_host, is_ht=ht_enabled,
                                                            vcpus_on_numa=post_vcpu_on_numa)

def test_compute_cpu_kernel_boot_args(hosts=None):
    """
    Check cpu config values in /proc/cmdline are inline with what's shown in system host-cpu-list
    Args:
        hosts (str|list|None):

    """
    if isinstance(hosts, str):
        hosts = [hosts]
    elif not hosts:
        hosts = host_helper.get_up_hypervisors()

    for host in hosts:
        is_lowlat = system_helper.is_lowlatency_host(host=host)
        funcs = ('Platform', 'vSwitch', None)
        platform_cores, vswitch_cores, all_cores = \
            host_helper.get_host_cpu_cores_for_function(hostname=host, func=funcs, thread=None, rtn_dict_per_proc=False)

        rcu_nocbs = list(set(all_cores) - set(platform_cores))
        expt_dict = {
            'rcu_nocbs': rcu_nocbs,
            'kthread_cpus': platform_cores,
            'irqaffinity': platform_cores,
            'isolcpus': rcu_nocbs if is_lowlat else vswitch_cores
        }

        LOG.info('---Check grub and cmdline args for cpu configs on {}'.format(host))
        with host_helper.ssh_to_host(hostname=host) as host_ssh:
            file = '/proc/cmdline'  # do not check /etc/default/grub since it's only the default
            output = host_ssh.exec_cmd('cat {}'.format(file), fail_ok=False)[1]
            for k, expt_v in expt_dict.items():
                actual_v = re.findall(r'{}=([\d\-,]+)(\s|$)'.format(k), output)
                assert actual_v, "{} match not found in {} on {}".format(k, file, host)
                actual_v = common.parse_cpus_list(cpus=actual_v[0][0])
                assert sorted(expt_v) == actual_v, \
                    "{}: {} in {} is different than expected. Items missing in grub: {}; extra items in grub: {}". \
                    format(host, k, file, list(set(expt_v) - set(actual_v)), list(set(actual_v) - set(expt_v)))


# -*- coding: utf-8 -*-
"""Command line program for EKT model training.
"""

from __future__ import unicode_literals, print_function, absolute_import

from .classifier import Clf
from .utils import read_dataset, write_html
from .utils import check_filename, save_classifier, load_classifier

import argparse
import sys
import logging
import codecs
import six

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('train')

parser = argparse.ArgumentParser(prog='textclassifier.retrain')
parser.add_argument(
    'dataset',
    help=('Dataset to use for training. Must contain columns defined in settings file.'
        ' It is possible to load .csv and .xlsx files.'))
parser.add_argument(
    'inmodel',
    help='The path of the original model.')
parser.add_argument(
    'outmodel',
    help='The path to store the updated model.')
parser.add_argument(
    '-t', '--treshold',
    type=float,
    default=0.0,
    help=('Confidence treshold. Only rows in extra dataset, where confidence >= treshold, will be used in merging.'))
parser.add_argument(
    '-r', '--report',
    help='The name of the report. The report is written as two files [name].html and [name]_misclassified_data.html')
parser.add_argument(
    '--sheet',
    default=0,
    help='Sheet name if loading data from Excel file (default read the first sheet).')
parser.add_argument(
    '--sep',
    default = ',',
    help='Column separator for CSV files (default is ,).')

class ReTrainerApp(object):

    def __init__(self, args):
        self._args = args

    def run(self):
        args = self._args
        check_filename(args.dataset)
        dataframe = read_dataset(args.dataset, args.sep, args.sheet)

        clf = load_classifier(args.inmodel)
        clf.retrain(dataframe, report=True if args.report is not None else False, conf_treshold=args.treshold)

        save_classifier(args.outmodel, clf)

        if args.report is not None:
            mainfnm = args.report + '.html'
            misclassfnm = args.report + '_misclassified_data.html'
            write_html(mainfnm, clf.report)
            write_html(misclassfnm, clf.misclassified_data)

        logger.info('Done!')

if __name__ == '__main__':
    app = ReTrainerApp(parser.parse_args())
    app.run()


import numpy as np
import pandas as pd

def student_ability(train_data, user_id):
	student_data = train_data[train_data.user_id.values==user_id]
	student_data=student_data[student_data.content_id.values==0]
	total_question = student_data.shape[0]
	correct_count = student_data[student_data.correct==1].shape[0]
	ability = correct_count/total_question
	return ability, correct_count, total_question

def update_ability(new_data, correct_count, total_question) :
	if new_data.correct == 1:
		correct_count +=1
		total_question +=1
	ability = correct_count/total_question
	return ability

def question_hardness(train_data, ques_id):
	ques_data = train_data[train_data.context_type==0]
	ques_data = ques_data[ques_data.content_id==ques_id]
	correct_count = ques_data[ques_data.correct == 1].shape[0]
	total = ques_data.shape[0]
	hardness = correct_count/total
	return hardness

def update_hardness(new_data, correct_count, total):
	if new_data.correct == 1:
		correct_count += 1
		total += 1
	hardness = correct_count/total
	return hardness


from PyQt5 import QtCore, QtWidgets
from ui_ErrorDialog import Ui_ErrorDialog

class ErrorDialog(QtWidgets.QDialog, Ui_ErrorDialog):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setFixedSize(300, 120)
        self.pushButton.clicked.connect(self.close)

    def set_error(self, text):
        self.label.setText(text)


# 将lianxi01.py中的函数封装成类
import random
import math

class GameNum():
    def line(self):
        str_num = ""
        for i in range(4):
            str_s = chr(random.randrange(97, 123))
            str_num += str_s
        for i in range(8):
            str_num += str(random.randrange(0, 10))
        return str_num

    def game(self, score, total, win):
        while True:
            random_num = random.randrange(100, 1000)
            num = input("请输入一个三位数, 输入-1退出游戏:")
            if num == "-1":
                print("游戏结束")
                break
            if num.isdigit() and 100 <= int(num) <= 999:
                total += 1
                print("有效输入累计次数:{0}".format(total))
                num = int(num)
                if num > random_num:
                    # 方法一
                    # bai = random_num % 100
                    # shi = random_num % 100 // 10
                    # ge = random_num % 100 % 10
                    # print("个位是{0},十位是{1},百位是{2}".format(ge, shi, bai))
                    # 方法二
                    bai = math.floor(random_num / 100)
                    shi = math.floor(random_num % 100 / 10)
                    ge = random_num % 100 % 10
                    print("你输入的数字过大,该随机数{0}的个位是{1},十位是{2},百位是{3}".format(random_num, ge, shi, bai))
                if num == random_num:
                    win += 1
                    score += 100
                    print("牛逼啊,目前得分{0}".format(score))
                    print("中奖概率为:{:.2f}%".format((win / total) * 100))
                if num < random_num:
                    print(random_num)
                    for i in range(10):
                        # 当实例化后,通过对象调用时
                        str_line = self.line()
                        # 当通过类直接调用时
                        # str_line = GameNum.line(0)
                        with open(r'str_num.txt', 'a') as f:
                            f.write(str_line + '\n')
            else:
                print("请按规定输入")

# 程序入口, 也叫调试代码
if __name__ == "__main__":
    score = 0
    total = 0
    win = 0
    # 实例化类,对象调用, 对象会自动作为参数传入函数
    game_num =GameNum()
    game_num.game(score, total, win)

    # 直接通过类调用,类不会将自身作为参数传入参数
    # 此处的'0'代表GameNum这个类自身
    # GameNum.game(0, score, total, win)


from itertools import permutations

inp = int(input())
l = list(permutations(list(str(inp))))
l.sort()

for i in l:
    if (int(''.join(i)) > inp):
        print(int(''.join(i)))
        exit()

print (0)


from decimal import Decimal
import logging
from typing import NoReturn

import discord
import discord.ext.commands as commands
import regex

from sandpiper.common.IANA import get_country_flag_emoji_from_timezone
from sandpiper.common.embeds import *
from sandpiper.common.misc import RuntimeMessages
from sandpiper.common.time import time_format
from sandpiper.conversion.time_conversion import *
import sandpiper.conversion.unit_conversion as unit_conversion
from sandpiper.user_data import DatabaseUnavailable, UserData

logger = logging.getLogger("sandpiper.unit_conversion")

conversion_pattern = regex.compile(
    # Skip anything inside a code block
    r"(?<!\\)`+(?s:.*?)`+(*SKIP)(*FAIL)|"
    # Match a {conversion block}
    r"{ *"
    r"(?P<quantity>[^>]+?) *"
    r"(?:> *(?P<out_unit>\S.*?) *)?"
    r"}"
)

class Conversion(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @commands.Cog.listener(name="on_message")
    async def conversions(self, msg: discord.Message):
        """
        Scan a message for conversion strings.

        :param msg: Discord message to scan for conversions
        """
        if msg.author == self.bot.user:
            return

        conversion_strs = conversion_pattern.findall(msg.content)
        if not conversion_strs:
            return

        conversion_strs = await self.convert_time(msg, conversion_strs)
        await self.convert_measurements(msg.channel, conversion_strs)

    async def convert_time(
        self, msg: discord.Message, time_strs: list[tuple[str, str]]
    ) -> list[tuple[str, str]]:
        """
        Convert a list of time strings (like "5:45 PM") to different users'
        timezones and reply with the conversions.

        :param msg: Discord message that triggered the conversion
        :param time_strs: a list of strings that may be valid times
        :returns: a list of strings that could not be converted
        """

        user_data: UserData = self.bot.get_cog("UserData")
        if user_data is None:
            # User data cog couldn't be retrieved, so consider all conversions
            # failed
            return time_strs

        try:
            db = await user_data.get_database()
        except DatabaseUnavailable:
            return time_strs

        runtime_msgs = RuntimeMessages()
        converted_times, failed = await convert_time_to_user_timezones(
            db, msg.author.id, msg.guild, time_strs, runtime_msgs=runtime_msgs
        )

        if runtime_msgs.exceptions:
            # Send embed with any errors that happened during conversion
            await ErrorEmbed([str(e) for e in runtime_msgs.exceptions], join="\n").send(
                msg.channel
            )
            return failed

        if converted_times:
            # Send successful conversions
            output = []
            for timezone_in, conversions in converted_times:
                # There may be multiple input timezones
                # We will group them under a header of that timezone name
                if timezone_in is not None:
                    # But if no input timezone was specified, don't print any
                    # header
                    output.append(f"Using timezone **{timezone_in}**")

                for timezone_out, times in conversions:
                    # Print the converted times for each timezone on a new line
                    times = "  |  ".join(
                        f"`{time.strftime(time_format)}`" for time in times
                    )
                    flag = get_country_flag_emoji_from_timezone(timezone_out)
                    output.append(f"{flag}  **{timezone_out}**  -  {times}")

                output.append("")

            await msg.channel.send("\n".join(output[:-1]))

        return failed

    async def convert_measurements(
        self, channel: discord.TextChannel, quantity_strs: list[tuple[str, str]]
    ) -> NoReturn:
        """
        Convert a list of quantity strings (like "5 km") between imperial and
        metric and reply with the conversions.

        :param channel: Discord channel to send conversions message to
        :param quantity_strs: a list of strings that may be valid quantities
        :returns: a list of strings that could not be converted
        """

        conversions = []
        failed: list[tuple[str, str]] = []
        runtime_msgs = RuntimeMessages()
        for qstr, unit in quantity_strs:
            q = unit_conversion.convert_measurement(
                qstr, unit, runtime_msgs=runtime_msgs
            )
            if isinstance(q, tuple):
                # We parsed as a quantity and got a conversion
                conversions.append(f"`{q[0]:.2f~P}` = `{q[1]:.2f~P}`")
            elif isinstance(q, Decimal):
                # We parsed as dimensionless and got a numeric type back
                conversions.append(f"`{qstr}` = `{q}`")
            else:
                failed.append((qstr, unit))

        if runtime_msgs.exceptions:
            # Send embed with any errors that happened during conversion
            await ErrorEmbed([str(e) for e in runtime_msgs.exceptions], join="\n").send(
                channel
            )

        if conversions:
            await channel.send("\n".join(conversions))


"""
Desarrollar un algoritmo que pida el nombre del usuario, el día, mes y año actual y el día, mes y año de nacimiento del
usuario. En  base a esos datos el algoritmo indica el signo zodiacal, la edad en horas y el número de la suerte del
usuario.

Autor: Natalia Gutiérrez Pineda.
"""

# Clase publica
class Numerologia:

    __anioNacimiento = int(0)
    __mesNacimiento = int(0)
    __diaNacimiento = int(0)
    __anioActual = int(0)
    __mesActual = int(0)
    __diaActual = int(0)
    __edad = int(0)
    __edadHoras = int(0)
    __signoZodiacal = str(" ")
    __numeroSuerte = int(0)

    # Metodo Constructor
    def __init__(self, anioNacimiento, mesNacimiento, diaNacimiento, anioActual, mesActual, diaActual):
        self.__anioNacimiento = anioNacimiento
        self.__mesNacimiento = mesNacimiento
        self.__diaNacimiento = diaNacimiento
        self.__anioActual = anioActual
        self.__mesActual = mesActual
        self.__diaActual = diaActual
        self.calcularEdad()
        self.identificarSignoZodiacal()
        self.calcularNumeroSuerte()

    # Getters
    def get_edad(self):
        return self.__edad

    def get_signoZodiacal(self):
        return self.__signoZodiacal

    def get_numeroSuerte(self):
        return self.__numeroSuerte

    # Metodos de instancia
    def calcularEdad(self):
        # Este metodo calculará la edad en horas del usuario.
        self.__edad = self.__anioActual - self.__anioNacimiento
        if (self.__mesActual < self.__mesNacimiento) or (
                self.__mesActual == self.__mesNacimiento and self.__diaActual < self.__diaNacimiento):
            self.__edad = self.__edad - 1
        self.__edad = self.__edad * 8760

    def identificarSignoZodiacal(self):
        # Este metodo identificará el signo zodiacal del usuario.
        if (self.__mesNacimiento == 12 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 1 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Capricornio'
        if (self.__mesNacimiento == 1 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 2 and self.__diaNacimiento <= 19):
            self.__signoZodiacal = 'Acuario'
        if (self.__mesNacimiento == 2 and self.__diaNacimiento >= 20) or (self.__mesNacimiento == 3 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Piscis'
        if (self.__mesNacimiento == 3 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 4 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Aries'
        if (self.__mesNacimiento == 4 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 5 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Tauro'
        if (self.__mesNacimiento == 5 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 6 and self.__diaNacimiento <= 21):
            self.__signoZodiacal = 'Géminis'
        if (self.__mesNacimiento == 6 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 7 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Cáncer'
        if (self.__mesNacimiento == 7 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 8 and self.__diaNacimiento <= 23):
            self.__signoZodiacal = 'Leo'
        if (self.__mesNacimiento == 8 and self.__diaNacimiento >= 24) or (self.__mesNacimiento == 9 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Virgo'
        if (self.__mesNacimiento == 9 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 10 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Libra'
        if (self.__mesNacimiento == 10 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 11 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Escorpio'
        if (self.__mesNacimiento == 11 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 12 and self.__diaNacimiento <= 21):
            self.__signoZodiacal = 'Sagitario'

    def calcularNumeroSuerte (self):
        # Este metodo calculará el numero de la suerte del usuario.
        while self.__anioNacimiento > 0:
            self. __numeroSuerte = self. __numeroSuerte + self.__anioNacimiento % 10
            self.__anioNacimiento = self.__anioNacimiento // 10

        while self.__numeroSuerte > 9:
            self.__numeroSuerte = self.__numeroSuerte - 9

    def __del__(self):
        print("Instancia destruida")

from abc import ABC

class abc(ABC):

    # Metodos de clase
    @classmethod
    def calcularEdadMC(cls, anioNacimiento, mesNacimiento, diaNacimiento, anioActual, mesActual, diaActual):
        # Este metodo calculará la edad en horas del usuario.
        edad = anioActual - anioNacimiento
        if (mesActual < mesNacimiento) or (
            mesActual == mesNacimiento and diaActual < diaNacimiento):
            edad = edad - 1

        return edad * 8760

    @classmethod
    def identificarSignoZodiacalMC(cls, mesNacimiento, diaNacimiento):
        # Este metodo identificará el signo zodiacal del usuario.
        signoZodiacal = " "
        if (mesNacimiento == 12 and diaNacimiento >= 22) or (mesNacimiento == 1 and diaNacimiento <= 20):
            signoZodiacal = 'Capricornio'
        if (mesNacimiento == 1 and diaNacimiento >= 22) or (mesNacimiento == 2 and diaNacimiento <= 19):
            signoZodiacal = 'Acuario'
        if (mesNacimiento == 2 and diaNacimiento >= 20) or (mesNacimiento == 3 and diaNacimiento <= 20):
            signoZodiacal = 'Piscis'
        if (mesNacimiento == 3 and diaNacimiento >= 21) or (mesNacimiento == 4 and diaNacimiento <= 20):
            signoZodiacal = 'Aries'
        if (mesNacimiento == 4 and diaNacimiento >= 21) or (mesNacimiento == 5 and diaNacimiento <= 20):
            signoZodiacal = 'Tauro'
        if (mesNacimiento == 5 and diaNacimiento >= 21) or (mesNacimiento == 6 and diaNacimiento <= 21):
            signoZodiacal = 'Géminis'
        if (mesNacimiento == 6 and diaNacimiento >= 22) or (mesNacimiento == 7 and diaNacimiento <= 22):
            signoZodiacal = 'Cáncer'
        if (mesNacimiento == 7 and diaNacimiento >= 23) or (mesNacimiento == 8 and diaNacimiento <= 23):
            signoZodiacal = 'Leo'
        if (mesNacimiento == 8 and diaNacimiento >= 24) or (mesNacimiento == 9 and diaNacimiento <= 22):
            signoZodiacal = 'Virgo'
        if (mesNacimiento == 9 and diaNacimiento >= 23) or (mesNacimiento == 10 and diaNacimiento <= 22):
            signoZodiacal = 'Libra'
        if (mesNacimiento == 10 and diaNacimiento >= 23) or (mesNacimiento == 11 and diaNacimiento <= 22):
            signoZodiacal = 'Escorpio'
        if (mesNacimiento == 11 and diaNacimiento >= 23) or (mesNacimiento == 12 and diaNacimiento <= 21):
            signoZodiacal = 'Sagitario'

        return signoZodiacal

    @classmethod
    def calcularNumeroSuerteMC(cls, anioNacimiento):
        # Este metodo calculará el numero de la suerte del usuario.
        numeroSuerte = 0
        while anioNacimiento > 0:
            numeroSuerte = numeroSuerte + anioNacimiento % 10
            anioNacimiento = anioNacimiento // 10

        while numeroSuerte > 9:
            numeroSuerte = numeroSuerte - 9

        return numeroSuerte

class Sobrecarga:

    __anioNacimiento = int(0)
    __mesNacimiento = int(0)
    __diaNacimiento = int(0)
    __anioActual = int(0)
    __mesActual = int(0)
    __diaActual = int(0)
    __edad = int(0)
    __edadHoras = int(0)
    __signoZodiacal = str(" ")
    __numeroSuerte = int(0)

    # Metodos de instancia
    def calcularEdad(self, anioNacimiento, mesNacimiento, diaNacimiento, anioActual, mesActual, diaActual):
        # Este metodo calculará la edad en horas del usuario.
        self.__anioNacimiento = anioNacimiento
        self.__mesNacimiento = mesNacimiento
        self.__diaNacimiento = diaNacimiento
        self.__anioActual = anioActual
        self.__mesActual = mesActual
        self.__diaActual = diaActual
        self.__edad = self.__anioActual - self.__anioNacimiento
        if (self.__mesActual < self.__mesNacimiento) or (
                self.__mesActual == self.__mesNacimiento and self.__diaActual < diaNacimiento):
            self.__edad = self.__edad - 1

        return self.__edad * 8760

    def identificarSignoZodiacal(self):
        # Este metodo identificará el signo zodiacal del usuario.
        if (self.__mesNacimiento == 12 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 1 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Capricornio'
        if (self.__mesNacimiento == 1 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 2 and self.__diaNacimiento <= 19):
            self.__signoZodiacal = 'Acuario'
        if (self.__mesNacimiento == 2 and self.__diaNacimiento >= 20) or (self.__mesNacimiento == 3 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Piscis'
        if (self.__mesNacimiento == 3 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 4 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Aries'
        if (self.__mesNacimiento == 4 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 5 and self.__diaNacimiento <= 20):
            self.__signoZodiacal = 'Tauro'
        if (self.__mesNacimiento == 5 and self.__diaNacimiento >= 21) or (self.__mesNacimiento == 6 and self.__diaNacimiento <= 21):
            self.__signoZodiacal = 'Géminis'
        if (self.__mesNacimiento == 6 and self.__diaNacimiento >= 22) or (self.__mesNacimiento == 7 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Cáncer'
        if (self.__mesNacimiento == 7 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 8 and self.__diaNacimiento <= 23):
            self.__signoZodiacal = 'Leo'
        if (self.__mesNacimiento == 8 and self.__diaNacimiento >= 24) or (self.__mesNacimiento == 9 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Virgo'
        if (self.__mesNacimiento == 9 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 10 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Libra'
        if (self.__mesNacimiento == 10 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 11 and self.__diaNacimiento <= 22):
            self.__signoZodiacal = 'Escorpio'
        if (self.__mesNacimiento == 11 and self.__diaNacimiento >= 23) or (self.__mesNacimiento == 12 and self.__diaNacimiento <= 21):
            self.__signoZodiacal = 'Sagitario'

        return self.__signoZodiacal

    def calcularNumeroSuerte(self):
        # Este metodo calculará el numero de la suerte del usuario.
        while self.__anioNacimiento > 0:
            self.__numeroSuerte = self.__numeroSuerte + self.__anioNacimiento % 10
            self.__anioNacimiento = self.__anioNacimiento // 10

        while self.__numeroSuerte > 9:
            self.__numeroSuerte = self.__numeroSuerte - 9

        return self.__numeroSuerte

    # Metodo con sobrecarga
    def numerologia(self, anioNacimiento=None, mesNacimiento=None, diaNacimiento=None, anioActual=None, mesActual=None, diaActual=None):
        if anioNacimiento is not None and mesNacimiento is not None and diaNacimiento is not None and anioActual is None and mesActual is None and diaActual is None:
            self.__anioNacimiento = anioNacimiento
            self.__mesNacimiento = mesNacimiento
            self.__diaNacimiento = diaNacimiento
            print(self.identificarSignoZodiacal())
            print(self.calcularNumeroSuerte())
            self.__numeroSuerte = 0
        elif anioNacimiento is not None and mesNacimiento is not None and diaNacimiento is not None and anioActual is not None and mesActual is not None and diaActual is not None:
            self.__anioNacimiento = anioNacimiento
            self.__mesNacimiento = mesNacimiento
            self.__diaNacimiento = diaNacimiento
            self.__anioActual = anioActual
            self.__mesActual = mesActual
            self.__diaActual = diaActual
            print(self.identificarSignoZodiacal())
            print(self.calcularNumeroSuerte())
            print(self.calcularEdad(2003, 7, 27, 2022, 4, 10))

    def __del__(self):
        print("Instancia destruida")

# Clase main
class Main:

    if __name__ == "__main__":
        # Instancia
        metodos = Numerologia(2003, 7, 27, 2022, 4, 10)
        # Llamado de los getters
        print(metodos.get_edad())
        print(metodos.get_signoZodiacal())
        print(metodos.get_numeroSuerte())
        # Llamado del destructor
        del metodos
        # Llamado de metodos de clase
        print(abc.calcularEdadMC(2003, 7, 27, 2022, 4, 10))
        print(abc.identificarSignoZodiacalMC(7, 27))
        print(abc.calcularNumeroSuerteMC(2003))
        # Instancia
        metodos2 = Sobrecarga()
        # Llamado del metodo con sobrecarga
        metodos2.numerologia(2000, 7, 27)
        metodos2.numerologia(2000, 7, 27, 2022, 4, 10)
        # Llamado del destructor
        del metodos2


from .basic_struct import StructBasic
from ctypes import *
import ctypes

BATCH_MAX_NUM = 32

#T_Block_Time_Info
class BlockTimeInfo(StructBasic):
    _fields_ = [("layer_sched_cyctime", ctypes.c_uint),
                ("layer_start_cyctime", ctypes.c_uint),
                ("layer_end_cyctime", ctypes.c_uint)]

    def bytes_sizeof(self):
        return ctypes.sizeof(BlockTimeInfo)

class LayerTypeInfo(StructBasic):
    _fields_ = [("block_type", ctypes.c_uint),
                ("dsp_layer_type", ctypes.c_uint)]

    def bytes_sizeof(self):
        return ctypes.sizeof(LayerTypeInfo)

class VecLayerTypeInfo(StructBasic):
    _fields_ = [("num", ctypes.c_int64),
                ("ptr", ctypes.POINTER(LayerTypeInfo))]

    @classmethod
    def from_bytes(_cls, _bytes, _offs=0):
        return _cls.get_vec_from_bytes(LayerTypeInfo, _bytes, _offs)

    def __init__(self, num=0):
        self.create_vec_struct(LayerTypeInfo, num)

    def bytes_sizeof(self):
        sz = ctypes.sizeof(ctypes.c_int64)
        sz += ctypes.sizeof(LayerTypeInfo) * self.num
        return sz

#std::vector<T_Block_Time_Info>
class VecTBlockTimeInfo(StructBasic):
    _fields_ = [("num", ctypes.c_int64),
                ("ptr", ctypes.POINTER(BlockTimeInfo))]

    @classmethod
    def from_bytes(_cls, _bytes, _offs = 0):
        return _cls.get_vec_from_bytes(BlockTimeInfo, _bytes, _offs)

    def __init__(self, num = 0):
        self.create_vec_struct(BlockTimeInfo, num)

    def bytes_sizeof(self):
        sz = ctypes.sizeof(ctypes.c_int64)
        sz += ctypes.sizeof(BlockTimeInfo) * self.num
        return sz

#T_Model_Time
class TModelTime(StructBasic):
    _fields_ = [("model_cyctime", ctypes.c_uint),
                ("model_time", ctypes.c_float),
                ("batchNum", ctypes.c_ushort),
                ("blockNum", ctypes.c_ushort),
                ("model_perbatch_cyctime", (ctypes.c_uint * BATCH_MAX_NUM)),
                ("model_start_cyctime", ctypes.c_uint),
                ("model_end_cyctime", ctypes.c_uint),
                ("block_cyctime", VecTBlockTimeInfo),
                ("layer_type", VecLayerTypeInfo)]

    @classmethod
    def from_bytes(_cls, _bytes, _offs = 0):
        model_cyctime = ctypes.c_uint.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint)

        model_time = ctypes.c_float.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_float)

        batchNum = ctypes.c_ushort.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_ushort)

        blockNum = ctypes.c_ushort.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_ushort)

        model_perbatch_cyctime = (ctypes.c_uint * BATCH_MAX_NUM).from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint * BATCH_MAX_NUM)

        model_start_cyctime = ctypes.c_uint.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint)

        model_end_cyctime = ctypes.c_uint.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint)

        block_cyctime = VecTBlockTimeInfo.from_bytes(_bytes, _offs)
        _offs += block_cyctime.bytes_sizeof()

        layer_type = VecLayerTypeInfo.from_bytes(_bytes, _offs)
        _offs += layer_type.bytes_sizeof()

        obj = _cls(model_cyctime,
                   model_time,
                   batchNum,
                   blockNum,
                   model_perbatch_cyctime,
                   model_start_cyctime,
                   model_end_cyctime,
                   block_cyctime,
                   layer_type)
        return obj

    def bytes_sizeof(self):
        sz = ctypes.sizeof(ctypes.c_uint) + ctypes.sizeof(ctypes.c_float) \
            + ctypes.sizeof(ctypes.c_ushort) * 2 + ctypes.sizeof(ctypes.c_uint * BATCH_MAX_NUM) \
            + ctypes.sizeof(ctypes.c_uint) * 2 + self.block_cyctime.bytes_sizeof() + self.layer_type.bytes_sizeof()
        return sz

#T_Model_Time
class DspProfileInfo(StructBasic):
    _fields_ = [("type", ctypes.c_int),
                ("reserved", ctypes.c_int),
                ("period_start_cycle", ctypes.c_uint64),
                ("period_end_cycle", ctypes.c_uint64),
                ("period_sched_rate", ctypes.c_double),
                ("tot_start_cycle", ctypes.c_uint64),
                ("tot_end_cycle", ctypes.c_uint64),
                ("tot_sched_rate", ctypes.c_double)]

    @classmethod
    def from_bytes(_cls, _bytes, _offs=0):
        type = ctypes.c_int.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_int)

        period_start_cycle = ctypes.c_uint64.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint64)

        period_end_cycle = ctypes.c_uint64.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint64)

        period_sched_rate = ctypes.c_double.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_double)

        tot_start_cycle = ctypes.c_uint64.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint64)

        tot_end_cycle = ctypes.c_uint64.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_uint64)

        tot_sched_rate = ctypes.c_double.from_buffer(_bytes, _offs)
        _offs += ctypes.sizeof(ctypes.c_double)

        obj = _cls(type,
                   period_start_cycle,
                   period_end_cycle,
                   period_sched_rate,
                   tot_start_cycle,
                   tot_end_cycle,
                   tot_sched_rate)
        return obj

#std::vector<DspProfileInfo>
class VecDspProfileInfo(StructBasic):
    _fields_ = [("num", ctypes.c_int64),
                ("ptr", ctypes.POINTER(DspProfileInfo))]

    @classmethod
    def from_bytes(_cls, _bytes, _offs = 0):
        return _cls.get_vec_from_bytes(DspProfileInfo, _bytes, _offs)

    def __init__(self, num = 0):
        self.create_vec_struct(DspProfileInfo, num)

    def bytes_sizeof(self):
        sz = ctypes.sizeof(ctypes.c_int64)
        sz += ctypes.sizeof(DspProfileInfo) * self.num
        return sz


from PyQt5 import QtWidgets
from furkan import Ui_MainWindow
import sys
import SSID

class App(QtWidgets.QMainWindow):
    def __init__(self):
        super(App,self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.kaydet.clicked.connect(self.kaydet)

    def kaydet(self):
        SSID.fonk()
        QtWidgets.QMessageBox.about(self,"","Kaydedildi")

def app():
    app = QtWidgets.QApplication(sys.argv)
    win = App()
    win.show()
    sys.exit(app.exec_())

app()


from typing import Dict, Any, Callable

from agent.evaluator import AEvaluator, IVModel, IQModel
from agent.planning_terminator import IPlanningTerminator
from misc.typevars import State, Action, Reward, Option, OptionData
from misc.utils import bool_random_choice

class SimpleMazeworldEvaluator(AEvaluator[State, Action, Reward, OptionData]):
    def __init__(self,
        planning_terminator: IPlanningTerminator[State, Action, Reward, OptionData],
        v_model: IVModel[State, Reward, OptionData],
        q_model: IQModel[State, Reward, OptionData],
        settings: Dict[str, Any],
        get_beta: Callable[[int], float],
        gamma: float):

        self.planning_terminator: IPlanningTerminator[State, Action, Reward, OptionData] = \
            planning_terminator
        super().__init__(v_model, q_model, settings, get_beta, gamma)

    def _should_use_raw_(self, state, option):
        return bool_random_choice(
            self.planning_terminator.termination_probability(state, option),
            self.random)


#!/bin/python3

import math
import os
import random
import re
import sys

class Rectangle:
    def __init__(self,l,b):
        self.l=l
        self.b=b
def area1(l,b):
        return int(l)*int(b)

class Circle:
    def __init__(self,r):
        self.r=r
def area2(r):
        return 3.14* int(r) * int(r)

if __name__ == '__main__':

    q = int(input())
    queries = []
    for _ in range(q):
        a=0
        b=0
        r=1
        args = input().split()
        shape_name, params = args[0], map(int, args[1:])
        if shape_name == "rectangle":
            a, b = map(int ,input().split(" "))
            shape = Rectangle(a, b)
        elif shape_name == "circle":
            r = map(int,input().split(" "))
            shape = Circle(r)
        else:
            raise ValueError("invalid shape type")
        print("%.2f\n" % area1(a,b))
        print("%.2f\n" % area2(r))

Hackerrank/HR certification test basic 1.py


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

def read_movie(file):
    print("Reading data")
    file_ext = file.split('.')[1]
    if file_ext == "tif":
        movie = tifffile.imread(file)
    elif file_ext == "nd2":
        movie = nd2.imread(file)
    return movie
def sum_movie(movie):
    print("Summing data")
    return np.sum(movie, axis = 0)
def find_spots(image, threshold, dist_limit = 3, background_subtract = True, spot_size = 3):
    #Needs improvement#
        #Spot finding parameter based on local maxima, but also consider circularity.
    print("Finding spots")
    row, col = image.shape
    initial_coordinates = []
    final_coordinates = []
    multiplier = 1000
    mthreshold = multiplier*threshold
    image_bgsub = np.zeros_like(image)
    if background_subtract == True:
        for y in range(spot_size, row - spot_size - 1):
            for x in range(spot_size, col - spot_size - 1):
                image_temp = image[y - spot_size:y + spot_size + 1, x - spot_size:x + spot_size + 1]
                image_bgsub[y - spot_size:y + spot_size + 1, x - spot_size: x + spot_size + 1] = image_temp - np.min(image_temp)
        image = image_bgsub
    for y in range(1, row - 1):
        for x in range(1, col - 1):
            row0 = image[y - 1, x]
            col0 = image[y, x - 1]
            pt = image[y, x ]
            row1 = image[y + 1, x]
            col1 = image[y, x + 1]
            if pt > mthreshold and pt > row0 and pt > row1 and pt > col0 and pt > col1:
                initial_coordinates.append((y, x))
    for set1 in initial_coordinates:
        y1, x1 = set1
        for set2 in initial_coordinates:
            y2, x2 = set2
            distance = np.sqrt((y2 - y1)**2 + (x2 - x1)**2)
            save = False
            if distance != 0:
                if distance >= dist_limit:
                    save = True
                elif distance < dist_limit:
                    break
        if save == True:
            final_coordinates.append(set1)
    print(f"Number of spots: {len(final_coordinates)}")
    return final_coordinates #saved as (y, x) or (row, column)

def extract_intensity(image, movie, coordinates, window_size = 10, smooth_window = 3, spot_size = 1, sigma = 1):

    print("Extracting intensity traces")
    intensity_data = []
    counter = 0
    saved_coordinates = []
    n = len(coordinates)
    def box_car_smoothing(intensity, smooth_window):
        boxcar = []
        for i in range(len(intensity) - smooth_window):
            boxcar.append(int(np.mean(intensity[i: i + smooth_window])))
        boxcar = np.pad(boxcar, (0, smooth_window), mode = 'edge')
        return boxcar
#Currently, the fit_intensity parameter is struggling the most at the moment. I need to figure out a way to improve the fitting parameter ... #
    def fit_intensity(intensity, window, sigma):
        print("fitting intensity traces")
        mean_data = int(np.mean(intensity))
        std_data = int(np.std(intensity))

        mean_list = []
        std_list = []
        for i in range(0 , len(intensity) - window, window):
            mean_window = np.mean(intensity[i: i + window])
            std_window = np.std(intensity[i: i + window])
            if mean_window < 2*mean_data and std_window < 2*std_data:
                mean_list.append(mean_window)
                std_list.append(std_window)
        mean_threshold = int(np.mean(mean_list))
        std_threshold = int(np.mean(std_list))

        change_points = [0]
        for j in range(window, len(intensity) - window, window):
            range1 = intensity[j - window: j]
            range2 = intensity[j: j + window]
            mean1 = int(np.mean(range1))
            mean2 = int(np.mean(range2))
            mean_difference = mean2 - mean1

            if mean2 > mean1 and mean_difference > sigma*std_threshold and mean_difference > 0.2*mean2:
                change_points.append(j)
            elif mean1 > mean2 and abs(mean_difference) > sigma*std_threshold and abs(mean_difference) > 0.2*mean1:
                change_points.append(j)
        change_points.append(len(intensity))

        fit = np.zeros_like(intensity)
        for k in range(len(change_points) - 1):
            range1 = change_points[k]
            range2 = change_points[k + 1]
            fit[range1:range2] = int(np.mean(intensity[range1:range2]))
        update = True
        while update:
            update = False
            for l in range(len(fit) - 1):
                range1 = fit[l]
                range2 = fit[l+1]
                difference = range2 - range1
                if difference != 0:
                    if difference > 0:
                        if 0.5*range2 < range1:
                            fit[l] = fit[l+1]
                            update = True
                    elif difference < 0:
                        if 0.5*range1 < range2:
                            fit[l+1] = fit[l]
                            update = True
        return fit
    fig = plt.figure(figsize = (17, 9))
    fig.subplots_adjust(left = 0.05, right = 0.95, bottom = 0.05, top = 0.95, wspace = 0.05, hspace = 0.25)
    #fig2 = plt.figure(figsize = (3,3))
    #ax1 = fig2.add_subplot(111)
    #ax1.imshow(image, cmap = 'gray')
    #ax1.set_title("Image")
    ax2 = fig.add_subplot(221)
    ax3 = fig.add_subplot(223, projection = '3d')
    ax4 = fig.add_subplot(222)
    ax5 = fig.add_subplot(224)
    for coordinate in coordinates:
        counter += 1
        print(f"processing {counter} of {len(coordinates)}")
        data = []
        y, x = coordinate
        frame_number = 0
        spot_frame1 = image[y - spot_size: y + spot_size + 1, x - spot_size: x + spot_size + 1]
        spot_frame2 = image[y - 2*spot_size: y + 2*spot_size + 1, x - 2*spot_size: x + 2*spot_size + 1]
        expanded_spot_frame1 = np.pad(spot_frame1, ((spot_size, spot_size)), mode = 'constant', constant_values = 0)
        bg = spot_frame2 - expanded_spot_frame1
        bg_int = np.mean(bg[bg > 0])
        spot_image = spot_frame2 - bg_int
        if spot_image.shape == (4*spot_size + 1, 4*spot_size + 1):
            for frame in movie:
                frame_number += 1
                spot_movie = frame[y - spot_size: y + spot_size + 1, x - spot_size: x + spot_size + 1]
                spot_bg = frame[y - 2*spot_size: y + 2*spot_size + 1, x - 2*spot_size: x + 2*spot_size + 1]
                spot_expand = np.pad(spot_movie, ((spot_size, spot_size), (spot_size, spot_size)), mode = 'constant', constant_values = 0)
                bg_diff = spot_bg - spot_expand
                bg_intensity = round(np.mean(bg_diff[bg_diff !=0]))
                spot_intensity = round(np.mean(spot_movie))
                passed_coordinate = coordinate
                data.append({'Frame': frame_number, 'Spot_intensity':spot_intensity, 'Background_intensity': bg_intensity, 'Background_subtract': spot_intensity - bg_intensity})
        data_df = pd.DataFrame(data)
        smooth = box_car_smoothing(data_df['Background_subtract'], smooth_window)
        fit = fit_intensity(data_df['Background_subtract'], window_size, sigma)
        fit_smooth = fit_intensity(smooth, smooth_window*window_size, sigma)
        data_df['Fit_intensity'] = fit
        data_df['Smooth_intensity'] = smooth
        data_df['Smooth_fit'] = fit_smooth
        #Plotting
        ystr, xstr = np.meshgrid(np.arange(4*spot_size + 1), np.arange(4*spot_size + 1))

        circles = plt.Circle((x,y), radius = 3, edgecolor = "red", fill = False, linewidth = 1)

        ax2.clear()
        ax3.clear()
        ax4.clear()
        ax5.clear()
        #ax1.add_artist(circles)
        #ax1.axis('off')
        ax2.imshow(spot_image, cmap = 'gray')
        ax2.axis('off')
        ax2.set_title(f"Spot {y}_{x}")
        ax3.plot_surface(xstr, ystr, spot_image)
        ax4.plot(data_df['Background_subtract'], color = 'black', label = "Data")
        ax4.plot(fit, color = 'red', label = "Fit")
        ax4.set_ylabel("Intensity")
        ax4.set_xlabel("Frame (Original)")
        ax5.plot(smooth, color = 'black', label = "Smooth data")
        ax5.plot(fit_smooth, color ='red',label = "Fit")
        ax5.set_ylabel("Intensity")
        ax5.set_xlabel(f"Frame (Boxcar smoothed: {smooth_window} frames)")
        plt.pause(0.5)
        plt.draw()
        save_spot = input("Save spot? (y/n)")
        if save_spot == "y":
            data_df.to_csv(f"spot_{y}_{x}.csv", index = False)
            plt.savefig(f"spot_{y}_{x}.png", dpi = 300, format = 'png', bbox_inches = 'tight')
        elif save_spot == "n":
            pass
    return


import requests
import tkinter
from tkinter import messagebox

# 入力値
def input_message():
    message = input_box.get()
    payload = {"value1":message}
    return payload

# IFTTT_Webhook
def webhook(eventid, payload):
    url = "https://maker.ifttt.com/trigger/" + eventid + "/with/key/dCm7Vg5DJEyLdAMxREVHdGAAWU0zwxPoru8tTH_1vC5"
    response = requests.post(url, data=payload)
    return response.status_code

def button_click():
    payload = input_message()

    if(webhook("message_post", payload) == 200):
        messagebox.showinfo("メッセージ送信","メッセージ送信完了しました")
    else:
        messagebox.showerror("エラー","メッセージ送信に失敗しました")

root = tkinter.Tk()
root.title("MainSender")
root.geometry("360x240")

input_label = tkinter.Label(text="メッセージ")
input_label.place(x=10, y=70)
input_box = tkinter.Entry(width=40)
input_box.place(x=10, y=100)
button = tkinter.Button(text="送信", command=button_click)
button.place(x=10, y=130)

root.mainloop()


vetor = []
vetor1 = []
vetor2 = []
for r in range(1, 11):
    valor1 = int(input(f'Informe o Valor Do Vetor1 {r}/10: '))
    vetor1.append(valor1)
    valor2 = int(input(f'Informe o Valor Do Vetor2 {r}/10: '))
    vetor2.append(valor2)
for valores in vetor1:
    if valores in vetor2:
      vetor.append(valores)
print(vetor)