import modeling
import logger
import ibm_hmc_lib
from appilog.common.system.types.vectors import ObjectStateHolderVector
from appilog.common.system.types import ObjectStateHolder
import storage_topology

#Defined shared modes in UCMDB
LPAR_SHARING_MODES = ['cap', 'uncap']
#mapping from the reported values of the CPU usage types to their UCMDB representation
LPAR_CPU_MODES = {'ded' : 'dedicated',
                  'shared' : 'shared'}
#Defines boot nodes in the UCMDB
LPAR_BOOT_MODES = ['norm', 'dd', 'ds', 'of', 'sms', 'not applicable']

class IbmVirtualScsiAdapter(storage_topology.ScsiAdapter):
    """
    The Data Object for the Virtual SCSI Adapter adopted to the HMC output
    Stores local and remote SCSI Adapter information
    """
    def __init__(self):
        storage_topology.ScsiAdapter.__init__(self)
        self.remoteLparId = None
        self.remoteLparName = None
        self.remoteSlotNumber = None

class IbmLparProfile:
    """
    This is a Data Object Class which represents the Lpar Profile and some other Lpar parameters.
    The attribute values of this class will be used to create OSHs of the "LPar Profile" CIT.
    """
    def __init__(self):
        self.name = "Lpar Profile"
        self.cpuMode = None
        self.uncapWeight = None
        self.connMonEnabled = None
        self.maxVirtSlots = None
        self.ioPoolIds = None
        self.desNumHugePages = None
        self.minNumHugePages = None
        self.maxNumHugePages = None
        self.desCpu = None
        self.minCpu = None
        self.maxCpu = None
        self.desPhysCpu = None
        self.minPhysCpu = None
        self.maxPhysCpu = None
        self.desMem = None
        self.minMem = None
        self.maxMem = None
        self.lparIpAddress = None
        self.virtSerialAdapters = None
        self.sharingMode = None

class IbmLpar:
    def __init__(self, lparProfile = None):
        self.lparProfile = lparProfile
        self.lparId = None
        self.lparName = None
        self.logicalSerialNumber = None
        self.type = None
        self.profileName = None
        self.state = None
        self.defaultProfName = None
        self.workgroupId = None
        self.bootMode = None
        self.autoStart = None
        self.powerCtrlIds = None
        self.redunErrPathRep = None
        self.sharedPoolId = None
        self.osName = None
        self.osVersion = None
        self.rmcIp = None

class GenericHost:
    def __init__(self, hostname = None, domainName = None):
        self.hostname = hostname
        self.domain_name = domainName
        self.gateway = None
        self.dns_servers = []
        self.ipList = []
        self.macs = []
        self.is_virtual = False
        self.serial = None
        self.board_uuid = None
        self.vendor = None
        self.model = None
        self.sys_obj_id = None
        self.architecture = None

class Host(GenericHost):
    def __init__(self, hostname = None, domainName = None):
        GenericHost.__init__(self, hostname, domainName)
        self.referenced_chassis = None
        self.chassis_slot = None
        self.fsmSoftware = None
        self.networking = None
        self.server_type = None
        self.sys_uuid = None
        self.name = None
        self.displayName = None
        self.managedSystem = None
        self.lpars_dict = None
        self.vm_id = None

    def __str__(self):
        return 'Host(hostname = "%s", domainName="%s", name = %s, is_virtual="%s")' % (self.hostname, self.domain_name, self.name, self.is_virtual)

    def __repr__(self):
        return self.__str__()

class StorageNode(GenericHost):
    def __init__(self, hostname = None):
        GenericHost.__init__(self, hostname, None)
        self.description = None
        self.node_name = None
        self.type = None
        self.os_version = None
        self.status = None
        self.version = None

    def __str__(self):
        return 'StorageNode(hostname = "%s"), ip = %s, serial = %s;' % (self.hostname, self.ipList, self.serial)

    def __repr__(self):
        return self.__str__()

class Switch(GenericHost):
    def __init__(self, hostname = None, domainName = None):
        GenericHost.__init__(self, hostname, domainName)

class FcSwitch(GenericHost):
    def __init__(self, hostname = None, domainName = None):
        GenericHost.__init__(self, hostname, domainName)

class Chassis(GenericHost):
    def __init__(self):
        GenericHost.__init__(self, None, None)
        self.id = None
        self.guid = None
        self.iface = []
        self.frim_level = None
        self.firm_build = None
        self.firm_name = None
        self.name = None

    def __str__(self):
        return 'Chassis(id = %s, ips = %s, hostname = %s, serial = %s)' % (self.id, self.ipList, self.hostname, self.serial)

    def __repr__(self):
        return self.__str__()

class FiberChannelHba:
    def __init__(self, name=None):
        self.name = name
        self.physPath = None
        self.descr = None
        self.wwn = None
        self.model = None
        self.serialNumber = None
        self.vendor = None

class Ip:
    def __init__(self, ipAddress = None, ipNetmask = None):
        self.ipAddress = ipAddress
        self.ipNetmask = ipNetmask

class LparNetworkInterface(modeling.NetworkInterface):
    def __init__(self):
        modeling.NetworkInterface.__init__(self, None, None)
        self.portVlanId = None
        self.lparName = None
        self.lparId = None
        self.isVirtual = None
        self.physicalPath = None
        self.interfaceType = None
        self.slotNum = None
        self.description = None
        self.operatingMode = None
        self.usedAdapters = []
        self.backupAdapter = None

class IbmFsm:
    """
    This is a Data Object Class which represents the IBM FSM management software.
    The attribute values of this class will be used to create OSHs of the "IBM HMC" CIT
    """
    def __init__(self, typeInformation, versionInformation):
        self.name = "IBM FSM"
        #self.bios = bios
        self.typeInformation = typeInformation
        self.vendor = 'ibm_corp'
        self.versionInformation = versionInformation
        self.osh = None

    def build(self, container):
        self.osh = createFsmSoftware(self, container)

class FsmTypeInformation:
    def __init__(self, fsmType, serialNum):
        self.fsmType = fsmType
        self.serialNum = serialNum

class VersionInformation:
    def __init__(self, shortVersion, fullVersion, baseOSVersion = None):
        self.shortVersion = shortVersion
        self.fullVersion = fullVersion
        self.baseOSVersion = baseOSVersion

########################################################################
##               BUILDER METHODS AND CLASSES
########################################################################

def createFsmHostOsh(fsmHost, ipAddress):
    """
    Creates the Object State Holder of the host where IBM HMC Management Sortware runs
    @param fsmHost: discovered host where IBM HMC runs
    @type fsmHost: instance of Host Data Object
    @param ipAddres: the IP Address of the Host
    @type ipAddress: String
    @return: Object State Holde of the UNIX CI instance
    """
    if fsmHost and ipAddress:
        hostOsh = modeling.createHostOSH(ipAddress, 'unix', None, fsmHost.hostname)
        hostOsh.setStringAttribute('vendor', 'ibm_corp')
        hostOsh.setStringAttribute("os_family", 'unix')
        if fsmHost.domainName:
            hostOsh.setStringAttribute('host_osdomain', fsmHost.domainName)
        if fsmHost.fsmSoftware:

#            if fsmHost.fsmSoftware.bios:
#                hostOsh.setStringAttribute('bios_serial_number', fsmHost.fsmSoftware.bios)

            if fsmHost.fsmSoftware.versionInformation:
                if fsmHost.fsmSoftware.versionInformation.fullVersion:
                    hostOsh.setStringAttribute('host_osrelease', fsmHost.fsmSoftware.versionInformation.fullVersion)
                if fsmHost.fsmSoftware.versionInformation.baseOSVersion:
                    hostOsh.setStringAttribute('discovered_os_version', fsmHost.fsmSoftware.versionInformation.baseOSVersion)

            if fsmHost.fsmSoftware.typeInformation and fsmHost.fsmSoftware.typeInformation.serialNum:
                hostOsh.setStringAttribute('serial_number', fsmHost.fsmSoftware.typeInformation.serialNum)

        return hostOsh
    else:
        logger.reportError('Failed to discover FSM Host')
        raise ValueError("Failed to discover FSM Host")

def createFsmSoftware(fsmSoftware, hostOsh):
    """
    Creates the Object State Holder of the IBM FSM Management Sortware
    @param fsmSoftware: the discovered IBM FSM
    @type fsmSoftware: instance of the IbmFsm Data Object
    @param hostOsh: host the FSM is running on
    @type hostOsh:  Object State Holder of the Host CI or any of its children
    @return: Object State Holder of the IBM FSM Management Sortware
    """
    if fsmSoftware:
        fsmOsh = modeling.createApplicationOSH('ibm_fsm', fsmSoftware.name, hostOsh, 'virtualization', 'ibm_corp')
#        if fsmSoftware.bios:
#            fsmOsh.setStringAttribute("fsm_bios", fsmSoftware.bios)
        if fsmSoftware.typeInformation.serialNum:
            fsmOsh.setStringAttribute("fsm_serial_number", fsmSoftware.typeInformation.serialNum)
        if fsmSoftware.typeInformation.fsmType:
            fsmOsh.setStringAttribute("fsm_type", fsmSoftware.typeInformation.fsmType)
        if fsmSoftware.versionInformation.shortVersion:
            fsmOsh.setStringAttribute("application_version_number", fsmSoftware.versionInformation.shortVersion)
        if fsmSoftware.versionInformation.fullVersion:
            fsmOsh.setStringAttribute("application_version", fsmSoftware.versionInformation.fullVersion)
        return fsmOsh

def createManagedSystemOsh(managedSystem, managedSystemOsh):
    """
    Creates the Object State Holder of the discovered Managed System
    @param managedSystem: discovered Managed System
    @type managedSystem: instance of the ManagedSystem Data Object
    @return: Object State Holder of the IBM PSeries Frame CI
    """
    if managedSystem and managedSystem.genericParameters and managedSystem.genericParameters.serialNumber:
        managedSystemOsh.setBoolAttribute("host_iscomplete", 1)
        managedSystemOsh.setStringAttribute("data_name", managedSystem.genericParameters.name)
        managedSystemOsh.setStringAttribute("host_key", managedSystem.genericParameters.serialNumber)
        managedSystemOsh.setStringAttribute("serial_number", managedSystem.genericParameters.serialNumber)
        managedSystemOsh.addAttributeToList("node_role", "server")
        managedSystemOsh.setStringAttribute("discovered_model", managedSystem.genericParameters.type_model)
        managedSystemOsh.setStringAttribute("vendor", "ibm_corp")
        managedSystemOsh.setStringAttribute("os_family", 'baremetal_hypervisor')
        if managedSystem.cpuParameters:
            if managedSystem.cpuParameters.minCpuPerVirtualCpu is not None:
                managedSystemOsh.setFloatAttribute("min_proc_units_per_virtual_proc", managedSystem.cpuParameters.minCpuPerVirtualCpu)
            if managedSystem.cpuParameters.curCpuAvail is not None:
                managedSystemOsh.setFloatAttribute("curr_avail_sys_proc_units", managedSystem.cpuParameters.curCpuAvail)
            if managedSystem.cpuParameters.maxSharedCpuPools is not None:
                managedSystemOsh.setIntegerAttribute("max_shared_proc_pools", managedSystem.cpuParameters.maxSharedCpuPools)
            if managedSystem.cpuParameters.maxOs400CpuUnits is not None:
                managedSystemOsh.setIntegerAttribute("max_os400_proc_units", managedSystem.cpuParameters.maxOs400CpuUnits)
            if managedSystem.cpuParameters.configurableCpuUnits is not None:
                managedSystemOsh.setFloatAttribute("configurable_sys_proc_units", managedSystem.cpuParameters.configurableCpuUnits)
            if managedSystem.cpuParameters.instCpuUnits is not None:
                managedSystemOsh.setFloatAttribute("installed_sys_proc_units", managedSystem.cpuParameters.instCpuUnits)
            if managedSystem.cpuParameters.pendingAvailCpuUnits is not None:
                managedSystemOsh.setFloatAttribute("pend_avail_sys_proc_units", managedSystem.cpuParameters.pendingAvailCpuUnits)
            if managedSystem.cpuParameters.maxCpuPerLpar is not None:
                managedSystemOsh.setIntegerAttribute("max_procs_per_lpar", managedSystem.cpuParameters.maxCpuPerLpar)
            if managedSystem.cpuParameters.maxVirtCpuPerLpar is not None:
                managedSystemOsh.setIntegerAttribute("max_virtual_procs_per_lpar", managedSystem.cpuParameters.maxVirtCpuPerLpar)

        if managedSystem.memoryParameters:
            if managedSystem.memoryParameters.configurableSysMem is not None:
                managedSystemOsh.setLongAttribute("configurable_sys_mem", managedSystem.memoryParameters.configurableSysMem)
            if managedSystem.memoryParameters.maxNumberHugePages is not None:
                managedSystemOsh.setIntegerAttribute("max_num_sys_huge_pages", managedSystem.memoryParameters.maxNumberHugePages)
            if managedSystem.memoryParameters.hugePageSize is not None:
                managedSystemOsh.setLongAttribute("huge_page_size", managedSystem.memoryParameters.hugePageSize)
            if managedSystem.memoryParameters.firmwareMem is not None:
                managedSystemOsh.setLongAttribute("sys_firmware_mem", managedSystem.memoryParameters.firmwareMem)
            if managedSystem.memoryParameters.memRegSize is not None:
                managedSystemOsh.setIntegerAttribute("mem_region_size", managedSystem.memoryParameters.memRegSize)
            if managedSystem.memoryParameters.currAvailMem is not None:
                managedSystemOsh.setLongAttribute("curr_avail_sys_mem", managedSystem.memoryParameters.currAvailMem)
            if managedSystem.memoryParameters.installedMem is not None:
                managedSystemOsh.setLongAttribute("installed_sys_mem", managedSystem.memoryParameters.installedMem)
            if managedSystem.memoryParameters.reqHugePagesNum is not None:
                managedSystemOsh.setLongAttribute("requested_num_sys_huge_pages", managedSystem.memoryParameters.reqHugePagesNum)
            if managedSystem.memoryParameters.pendingAvailMem is not None:
                managedSystemOsh.setLongAttribute("pend_avail_sys_mem", managedSystem.memoryParameters.pendingAvailMem)

        if managedSystem.genericParameters.codCpuCapable is not None:
            managedSystemOsh.setIntegerAttribute("cod_proc_capable", managedSystem.genericParameters.codCpuCapable)
        if managedSystem.genericParameters.codMemCapable is not None:
            managedSystemOsh.setIntegerAttribute("cod_mem_capable", managedSystem.genericParameters.codMemCapable)
        if managedSystem.genericParameters.hugeMemCapable is not None:
            managedSystemOsh.setBoolAttribute("huge_page_mem_capable", managedSystem.genericParameters.hugeMemCapable)
        if managedSystem.genericParameters.maxLpars is not None:
            managedSystemOsh.setIntegerAttribute("max_lpars", managedSystem.genericParameters.maxLpars)
        if managedSystem.genericParameters.microLparCape is not None:
            managedSystemOsh.setBoolAttribute("micro_lpar_capable", managedSystem.genericParameters.microLparCape)
        if managedSystem.genericParameters.servLparId is not None:
            managedSystemOsh.setIntegerAttribute("service_lpar_id", managedSystem.genericParameters.servLparId)
        if managedSystem.genericParameters.servLparName:
            managedSystemOsh.setStringAttribute("service_lpar_name", managedSystem.genericParameters.servLparName)

def createLparProfileOsh(lparProfile, hostOsh):
    """
    Creates the Lpar Profile Object State Holder
    @param lparProfile: the discovered parameters of the Lpar or VIO Server
    @type lparProfile: instance of the LparProfile Data Object
    @param hostOsh: lpar of vio server host
    @type hostOsh:  Object State Holder of the Host CI or any of its children
    @return: Object State Holder for the LPar Profile
    """
    if lparProfile:
        lparProfileOsh = ObjectStateHolder('ibm_lpar_profile')
        lparProfileOsh.setStringAttribute('data_name', lparProfile.lparProfile.name)
        lparProfileOsh.setContainer(hostOsh)
        if lparProfile.logicalSerialNumber:
            lparProfileOsh.setStringAttribute('logical_serial_number', lparProfile.logicalSerialNumber)
        if lparProfile.lparProfile.sharingMode:
            lparProfileOsh.setStringAttribute('sharing_mode', lparProfile.lparProfile.sharingMode)
        if lparProfile.lparProfile.cpuMode:
            lparProfileOsh.setStringAttribute('proc_mode', lparProfile.lparProfile.cpuMode)
        if lparProfile.lparProfile.uncapWeight is not None:
            lparProfileOsh.setIntegerAttribute('uncap_weight', lparProfile.lparProfile.uncapWeight)
        if lparProfile.powerCtrlIds:
            lparProfileOsh.setStringAttribute('power_ctrl_lpar_ids', lparProfile.powerCtrlIds)
        if lparProfile.bootMode:
            lparProfileOsh.setStringAttribute('boot_mode', lparProfile.bootMode)
        if lparProfile.lparProfile.connMonEnabled is not None:
            lparProfileOsh.setBoolAttribute('conn_monitoring', lparProfile.lparProfile.connMonEnabled)
        if lparProfile.lparProfile.maxVirtSlots is not None:
            lparProfileOsh.setIntegerAttribute('max_virtual_slots', lparProfile.lparProfile.maxVirtSlots)
        if lparProfile.autoStart is not None:
            lparProfileOsh.setBoolAttribute('auto_start', lparProfile.autoStart)
        if lparProfile.lparProfile.ioPoolIds:
            lparProfileOsh.setStringAttribute('lpar_io_pool_ids', lparProfile.lparProfile.ioPoolIds)
        if lparProfile.redunErrPathRep is not None:
            lparProfileOsh.setBoolAttribute('redundant_err_path_reporting', lparProfile.redunErrPathRep)
        if lparProfile.lparProfile.desNumHugePages is not None:
            lparProfileOsh.setIntegerAttribute('desired_num_huge_pages', lparProfile.lparProfile.desNumHugePages)
        if lparProfile.lparProfile.minNumHugePages is not None:
            lparProfileOsh.setIntegerAttribute('min_num_huge_pages', lparProfile.lparProfile.minNumHugePages)
        if lparProfile.lparProfile.maxNumHugePages is not None:
            lparProfileOsh.setIntegerAttribute('max_num_huge_pages', lparProfile.lparProfile.maxNumHugePages)
        if lparProfile.lparProfile.desCpu is not None:
            lparProfileOsh.setIntegerAttribute('desired_procs', lparProfile.lparProfile.desCpu)
        if lparProfile.lparProfile.minCpu is not None:
            lparProfileOsh.setIntegerAttribute('min_procs', lparProfile.lparProfile.minCpu)
        if lparProfile.lparProfile.maxCpu is not None:
            lparProfileOsh.setIntegerAttribute('max_procs', lparProfile.lparProfile.maxCpu)
        if lparProfile.lparProfile.desPhysCpu is not None:
            lparProfileOsh.setFloatAttribute('desired_proc_units', lparProfile.lparProfile.desPhysCpu)
        if lparProfile.lparProfile.minPhysCpu is not None:
            lparProfileOsh.setFloatAttribute('min_proc_units', lparProfile.lparProfile.minPhysCpu)
        if lparProfile.lparProfile.maxPhysCpu is not None:
            lparProfileOsh.setFloatAttribute('max_proc_units', lparProfile.lparProfile.maxPhysCpu)
        if lparProfile.lparProfile.desMem is not None:
            lparProfileOsh.setLongAttribute('desired_mem', lparProfile.lparProfile.desMem)
        if lparProfile.lparProfile.minMem is not None:
            lparProfileOsh.setLongAttribute('min_mem', lparProfile.lparProfile.minMem)
        if lparProfile.lparProfile.maxMem is not None:
            lparProfileOsh.setLongAttribute('max_mem', lparProfile.lparProfile.maxMem)
        if lparProfile.workgroupId:
            lparProfileOsh.setStringAttribute('work_group_id', lparProfile.workgroupId)
        if lparProfile.defaultProfName:
            lparProfileOsh.setStringAttribute('default_profile_name', lparProfile.defaultProfName)
        if lparProfile.profileName:
            lparProfileOsh.setStringAttribute('profile_name', lparProfile.profileName)
        if lparProfile.state:
            lparProfileOsh.setStringAttribute('lpar_state', lparProfile.state)
        if lparProfile.type:
            lparProfileOsh.setStringAttribute('lpar_type', lparProfile.type)
        if lparProfile.lparId is not None:
            lparProfileOsh.setIntegerAttribute('lpar_id', lparProfile.lparId)
        if lparProfile.lparName:
            lparProfileOsh.setStringAttribute('lpar_name', lparProfile.lparName)
        if lparProfile.lparProfile.virtSerialAdapters:
            lparProfileOsh.setStringAttribute('virtual_serial_adapters', lparProfile.lparProfile.virtSerialAdapters)
        return lparProfileOsh

ARCHITECTURE_TRANSFORMATION = {'x86_64': '64-bit', 'ppc64' : 'ppc64', 'x86' : '32-bit','x86_32': '32-bit'}
def buildGenericHostObject(host_class, hostDo,  report_serial = True):
    if not host_class:
        raise ValueError('Failed to create Node no host class passed')

    host_osh = ObjectStateHolder(host_class)

    if hostDo.hostname:
        host_osh.setStringAttribute('name', hostDo.hostname)

    host_osh.setBoolAttribute('host_iscomplete', 1)
    key = hostDo.hostname or hostDo.ipList
    if hostDo.domain_name:
        host_osh.setStringAttribute('domain_name', hostDo.domain_name)

    if hostDo.is_virtual:
        host_osh.setBoolAttribute('host_isvirtual', 1)

    if hostDo.serial and report_serial:
        host_osh.setStringAttribute('serial_number', hostDo.serial)

    if hostDo.model:
        host_osh.setStringAttribute('discovered_model', hostDo.model)

    if hostDo.vendor:
        host_osh.setStringAttribute('discovered_vendor', hostDo.vendor)

    if hostDo.sys_obj_id:
        host_osh.setStringAttribute('sys_object_id', hostDo.sys_obj_id)

    if hostDo.architecture and ARCHITECTURE_TRANSFORMATION.get(hostDo.architecture):
        host_osh.setStringAttribute('os_architecture', ARCHITECTURE_TRANSFORMATION.get(hostDo.architecture))

    return host_osh

def buildChassis(hostDo):
    chassis_osh = buildGenericHostObject('chassis', hostDo)

    if not hostDo.hostname and hostDo.name:
        chassis_osh.setStringAttribute('name', hostDo.name)
    if hostDo.guid:
        chassis_osh.setStringAttribute('chassis_uniqueid', hostDo.guid)

    if hostDo.model:
        chassis_osh.setStringAttribute('chassis_model', hostDo.model)

    if hostDo.vendor:
        chassis_osh.setStringAttribute('chassis_vendor', hostDo.vendor)

    description = "Firmware %s, build %s, level %s" % (hostDo.firm_name or '', hostDo.firm_build or '', hostDo.frim_level or '')
    chassis_osh.setStringAttribute('discovered_description', description)

    return chassis_osh

def reportChassis(hostDo, fsm_osh):
    if not fsm_osh:
        raise ValueError('Failed to report Chassis. No FSM OSH passed')
    vector = ObjectStateHolderVector()
    chassis_osh = buildChassis(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, chassis_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', chassis_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
    vector.add(chassis_osh)
    return vector, chassis_osh

def buildVirtualMachine(hostDo):
    vm_osh = buildGenericHostObject('host_node', hostDo)
    vm_osh.setStringAttribute("os_family", 'unix')
    if not hostDo.hostname:
        vm_osh.setStringAttribute('name', hostDo.name)
    if hostDo.sys_uuid:
        vm_osh.setStringAttribute('discovered_description', hostDo.sys_uuid)
    return vm_osh

def reportVirtualMachine(vm_map, server, server_osh, host_class, lpar, server_serial_to_interfaces):
    vector = ObjectStateHolderVector()
    key = '%s%s' % (server.serial, lpar.lparId)
    hostDo = vm_map.get(key)

    if not hostDo:
        logger.warn('Failed to report lpar with id %s and name %s' % (lpar.lparId, lpar.lparName))
        return vector, None

    vm_osh = buildGenericHostObject(host_class, hostDo, False)
    if lpar.type != 'os400':
        vm_osh.setStringAttribute("os_family", 'unix')

    if lpar.logicalSerialNumber:
        vm_osh.setStringAttribute('serial_number', lpar.logicalSerialNumber)
    elif hostDo.serial:
        vm_osh.setStringAttribute('serial_number', 'derived:%s' % hostDo.serial)

    if hostDo.ipList:
        vm_osh.setStringAttribute('host_key', str(hostDo.ipList[0]))
    if not hostDo.ipList and hostDo.macs:
        vm_osh.setStringAttribute('host_key', str(hostDo.macs[0]))
    hypervisor_osh = createIbmHypervisorOsh(server_osh)
    link_osh = modeling.createLinkOSH('execution_environment', hypervisor_osh, vm_osh)
    vector.add(vm_osh)
    vector.add(hypervisor_osh)
    vector.add(link_osh)
    if lpar.rmcIp:
        hostDo.ipList.append(lpar.rmcIp)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            #logger.debug('Reporting %s ip for lpar %s' % (ip, hostDo.displayName))
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', vm_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    interfaces_map = server_serial_to_interfaces.get(hostDo.serial, {})
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, vm_osh)
            vector.add(interface_osh)
            server_iface_osh = interfaces_map.get(mac)
            if server_iface_osh:
                link_osh = modeling.createLinkOSH('realization', interface_osh, server_iface_osh)
                vector.add(link_osh)

    return vector, vm_osh

def buildServer(hostDo):
    server_osh = buildGenericHostObject('ibm_pseries_frame', hostDo)
    server_osh.setStringAttribute("os_family", 'baremetal_hypervisor')
    if hostDo.server_type:
        server_osh.setStringAttribute('discovered_description', hostDo.server_type)
    if hostDo.displayName:
        server_osh.setStringAttribute('name', hostDo.displayName)
    if hostDo.managedSystem:
        createManagedSystemOsh(hostDo.managedSystem, server_osh)
    return server_osh

def reportServer(hostDo, chassis_map):
    vector = ObjectStateHolderVector()
    server_osh = buildServer(hostDo)
    chassis_osh = chassis_map.get(hostDo.referenced_chassis)
    if not chassis_osh:
        logger.warn('Failed to get referenced chassis "%s" for server %s. Server will not be reported.' % (hostDo.referenced_chassis, hostDo))
        return vector, None, {}
    link_osh = modeling.createLinkOSH('containment', chassis_osh, server_osh)
    vector.add(server_osh)
    vector.add(chassis_osh)
    vector.add(link_osh)

    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', server_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, server_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh

    if hostDo.managedSystem:
        if hostDo.managedSystem.cpuParameters and hostDo.managedSystem.cpuParameters.instCpuUnits:
            for i in xrange(int(hostDo.managedSystem.cpuParameters.instCpuUnits)):
                cpuOsh = modeling.createCpuOsh('CPU' + str(i), server_osh)
                # We treat a core as a physical CPU, so set core_number to 1
                cpuOsh.setIntegerAttribute("core_number", 1)
                vector.add(cpuOsh)

        if hostDo.managedSystem.ioSlotList:
            for ioSlot in hostDo.managedSystem.ioSlotList:
                vector.add(ibm_hmc_lib.createIoSlotOsh(ioSlot, server_osh))

    return vector, server_osh, iface_mac_to_iface_osh

def createIbmHypervisorOsh(managedSystemOsh):
        """
        Creates the IBM Hypervisor Object State Holder
        @param managedSystemOsh: the discovered Managed System the Hypervisor is runnig on
        @type managedSystemOsh: OSH instance of the Node which acts as a host for the VM
        @return: Object State Holder for IBM Hypervisor
        """
        return modeling.createApplicationOSH('virtualization_layer', "IBM Hypervisor", managedSystemOsh, None, "ibm_corp")

def buildSwitch(hostDo):

    switch_osh = buildGenericHostObject('switch', hostDo)

    return switch_osh

def reportSwitch(hostDo, chassis_map, server_map, fsm_osh):
    vector = ObjectStateHolderVector()
    switch_osh = buildSwitch(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, switch_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', switch_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)

    iface_mac_to_iface_osh = {}
    if hostDo.macs:
        for mac in hostDo.macs:
            interface_osh = modeling.createInterfaceOSH(mac, switch_osh)
            vector.add(interface_osh)
            iface_mac_to_iface_osh[mac] = interface_osh
    return vector, switch_osh

def buildFcSwitch(hostDo):
    switch_osh = buildGenericHostObject('fcsswitch', hostDo)
    return switch_osh

def reportFcSwitch(hostDo, chassis_map, server_map):
    pass

def buildStorageSystem(hostDo):
    storage_osh = buildGenericHostObject('storagearray', hostDo)
    return storage_osh

def reportStorageSystem(hostDo, fsm_osh):
    vector = ObjectStateHolderVector()
    storage_osh = buildStorageSystem(hostDo)
    link_osh = modeling.createLinkOSH('manage', fsm_osh, storage_osh)
    vector.add(link_osh)
    if hostDo.ipList:
        for ip in hostDo.ipList:
            ip_osh = modeling.createIpOSH(ip)
            link_osh = modeling.createLinkOSH('containment', storage_osh, ip_osh)
            vector.add(ip_osh)
            vector.add(link_osh)
    vector.add(storage_osh)
    return vector, storage_osh

def createRemoteScsiAdapterOsh(vScsi, remoteLparOsh):
    """
    Creates Object State Holder for SCSI Adapter CI on the remote LPar
    @param scsiAdapter: the discovered SCSI Adapter
    @type scsiAdapter: instance of the ScsiAdapter Data Object
    @param remoteLparOsh: Object State Holder of the Host this SCSI Adapter belongs to
    @type remoteLparOsh: OSH instance of a Host CI or any of its siblings
    @return: SCSI Adapter OSH
    """
    if vScsi and remoteLparOsh:
        remoteScsi = storage_topology.ScsiAdapter()
        remoteScsi.isVirtual = 1
        remoteScsi.slotNumber = vScsi.remoteSlotNumber
        remoteScsi.type = 'client'
        return storage_topology.createScsiAdapterOsh(remoteScsi, remoteLparOsh)

def createProcessorPoolOsh(processorPool, hypervisorOsh):
    """
    Creates Shared Processor Pool Object State Holder
    @param processorPool: the discovered Shared Processor Pool
    @type processorPool: instance of the IbmProcessorPool Data Object
    @param hypervisorOsh:
    @type hypervisorOsh:
    @return: Object State Holder of the IBM Processor Pool CI
    """
    if processorPool and processorPool.name and hypervisorOsh:
        processorPoolOsh = ObjectStateHolder('ibm_resource_pool')
        processorPoolOsh.setContainer(hypervisorOsh)
        processorPoolOsh.setStringAttribute('data_name', processorPool.name)
        processorPoolOsh.setStringAttribute('pool_id', processorPool.name)
        if processorPool.physCpuAvail is not None:
            processorPoolOsh.setFloatAttribute('physical_cpus_available', processorPool.physCpuAvail)
        if processorPool.physCpuConf is not None:
            processorPoolOsh.setFloatAttribute('physical_cpus_configurable', processorPool.physCpuConf)
        if processorPool.physCpuPendingAvail is not None:
            processorPoolOsh.setFloatAttribute('physical_cpus_pending', processorPool.physCpuPendingAvail)
        return processorPoolOsh

def getHostClassByEnvType(type):
    '''
    @param type: String value of env_type partition parameter
    @type : String
    @return: String value of Host class for the type
    '''
    if type == 'os400':
        return 'as400_node'
    return 'unix'

def ReportTopology(chassises, servers, system_pools, vms, switches, storages, fsm_osh, reportHostName):
    vector = ObjectStateHolderVector()
    vector.add(fsm_osh)

    vm_map = {}
    for vm in vms:
        key = '%s%s' % (vm.serial, vm.vm_id)
        vm_map[key] = vm
    chassis_name_to_chassis_osh = {}
    server_serial_to_server_osh = {}
    server_serial_to_interfaces = {}
    if chassises:
        for chassis in chassises:
            vect, chassis_osh = reportChassis(chassis, fsm_osh)
            chassis_name_to_chassis_osh[chassis.name] = chassis_osh
            if chassis.name and chassis.name.find(' ') != -1:
                chassis_name_to_chassis_osh[chassis.name[:chassis.name.find(' ')]] = chassis_osh
            vector.addAll(vect)

    if servers:
        for server in servers:
            vect, server_osh, iface_map = reportServer(server, chassis_name_to_chassis_osh)
            if not server_osh:
                continue
            vector.addAll(vect)
            server_serial_to_server_osh[server.serial] = server_osh
            server_serial_to_interfaces[server.serial] = iface_map
            #report cpu pools
            cpuPoolOshDict = {}
            hypervisor_osh = createIbmHypervisorOsh(server_osh)
            if server.managedSystem and server.managedSystem.cpuPoolList:
                cpuQuont = 0
                for processorPool in server.managedSystem.cpuPoolList:
                    processorPoolOsh = createProcessorPoolOsh(processorPool, hypervisor_osh)
                    vector.add(processorPoolOsh)
                    cpuPoolOshDict[processorPool.name] = processorPoolOsh
                    if processorPool.physCpuConf:
                        cpuQuont += int(processorPool.physCpuConf)
                        for i in xrange(cpuQuont):
                            cpuOsh = modeling.createCpuOsh('CPU' + str(i), server_osh)
                            linkOsh = modeling.createLinkOSH('contained', processorPoolOsh, cpuOsh)
                            vector.add(linkOsh)
            #reporting vms
            lparOshDict = {}
            if server.managedSystem.lparProfilesDict:
                for lpar in server.managedSystem.lparProfilesDict.values():
                    if lpar.type not in ('aixlinux', 'os400', 'vioserver'):
                        continue
                    #if lpar.lparProfile.lparIpAddress or (reportHostName and reportHostName.lower().strip() == 'true'):
                    #creating Lpar
#                        virtualHostOsh = modeling.createHostOSH(lpar.lparProfile.lparIpAddress, 'host', lpar.osName)
                    virtualHostOsh = None
                    host_class = getHostClassByEnvType(lpar.type)

                    vect, virtualHostOsh = reportVirtualMachine(vm_map, server, server_osh, host_class, lpar, server_serial_to_interfaces)
                    vector.addAll(vect)

                    if not virtualHostOsh:
                        logger.warn('Failed to create Lpar %s ' % lpar.lparName)
                        continue

                    if reportHostName and reportHostName.lower().strip() == 'true':
                        virtualHostOsh.setStringAttribute('name', lpar.lparName)

                    lparOshDict[lpar.lparId] = virtualHostOsh
                    vector.add(virtualHostOsh)
                    #creating Lpar Profile
                    lparProfileOsh = createLparProfileOsh(lpar, virtualHostOsh)
                    vector.add(lparProfileOsh)
                    #Linking Lpar to Shared Pool
                    if lpar.sharedPoolId and cpuPoolOshDict.has_key(lpar.sharedPoolId):
                        linkOsh = modeling.createLinkOSH('use', virtualHostOsh, cpuPoolOshDict[lpar.sharedPoolId])
                        vector.add(linkOsh)

            if server.managedSystem.vScsiList:
                for vScsi in server.managedSystem.vScsiList:
                    localLparOsh = lparOshDict.get(vScsi.parentId)
                    remoteLparOsh = lparOshDict.get(vScsi.remoteLparId)
                    if localLparOsh and remoteLparOsh:
                        localVScsiOsh = storage_topology.createScsiAdapterOsh(vScsi, localLparOsh)
                        remoteVScsiOsh = createRemoteScsiAdapterOsh(vScsi, remoteLparOsh)
                        linkOsh = modeling.createLinkOSH('use', remoteVScsiOsh, localVScsiOsh)
                        vector.add(localVScsiOsh)
                        vector.add(remoteVScsiOsh)
                        vector.add(linkOsh)
                        # create and link v I/O Slot to vSCSI
                        for vIoSlot in server.managedSystem.vIoSlotList:
                            if vIoSlot.slotType == 'scsi' and vIoSlot.lpar_id == vScsi.parentId and vIoSlot.slotNum == vScsi.slotNumber:
                                vIoSlotOsh = ibm_hmc_lib.createIoSlotOsh(vIoSlot, localLparOsh)
                                linkOsh = modeling.createLinkOSH('contained', vIoSlotOsh, localVScsiOsh)
                                vector.add(vIoSlotOsh)
                                vector.add(linkOsh)
                            if vIoSlot.slotType == 'scsi' and vIoSlot.lpar_id == vScsi.remoteLparId and vIoSlot.slotNum == vScsi.remoteSlotNumber:
                                vIoSlotOsh = ibm_hmc_lib.createIoSlotOsh(vIoSlot, remoteLparOsh)
                                linkOsh = modeling.createLinkOSH('contained', vIoSlotOsh, remoteVScsiOsh)
                                vector.add(vIoSlotOsh)
                                vector.add(linkOsh)

    if storages:
        for subsystem in storages:
            vect, subsystem_osh = reportStorageSystem(subsystem, fsm_osh)
            vector.addAll(vect)

    if switches:
        for switch in switches:
            try:
                vect, sw_osh = reportSwitch(switch, chassis_name_to_chassis_osh, server_serial_to_interfaces, fsm_osh)
            except:
                logger.debug("Failed to report Switch. Data missing.")

    return vector


# Задача 0. Дано число N. Найти все его делители. Для каждого делителя укажите, четный он или нечетный

def check_even(x):
    if x % 2 == 0:
        return "– четное"
    else:
        return "– нечетное"

# def find_div(x):
    values = range(1, x+1)
    for i in values:
        if x % i == 0:
            print(i, check_even(i))

def find_div(x):
    values = range(1, x+1)
    result = []
    for i in values:
        if x % i == 0:
            result.append(i)

number = int(input("Введите число: "))
# find_div(number)

divisors = find_div(number)
for i in divisors:
    print(i, check_even(i))


from datetime import datetime

WINS = 0
LOSSES = 1
TIES = 2

class Location:
    def __init__(self, city, state, country):
        self.city = city
        self.state = state
        self.country = country

    def getLocationString(self):
        return self.city + ", " + self.state + ", " + self.country

class Team(Location):
    def __init__(self, team_number):
        self.team_number = team_number
        self.key = "frc" + str(team_number)
        self.attrs = {}
        self.event_keys = []
        self.event_wlt = {} # event -> (# wins, # loss, # ties)
        self.event_wins = {} # year -> [event, ...]
        for year in range(1992, 2030):
            self.event_wins[year] = []

    def loadTBAData(self, team_tba_data):
        self.name = team_tba_data.name
        self.nickname = team_tba_data.nickname
        self.city = team_tba_data.city
        self.state = team_tba_data.state_prov
        self.country = team_tba_data.country

    def loadEventWLT(self, event):
        if event.key not in self.event_keys:
            self.event_keys.append(event.key)
        # WLT
        self.event_wlt[event.key] = [0, 0, 0]
        for match in event.matches.values():
            if not match.finished:
                continue
            if self.key in match.red_teams:
                self.event_wlt[event.key][0 if match.winning_alliance == 'red' else 1 if match.winning_alliance == 'blue' else 2] += 1
            elif self.key in match.blue_teams:
                self.event_wlt[event.key][0 if match.winning_alliance == 'blue' else 1 if match.winning_alliance == 'red' else 2] += 1
        # Event Win
        winning_alliance = event.getWinningAlliance()
        if winning_alliance == None:
            return
        if self.key in winning_alliance.team_keys:
            self.event_wins[event.year].append(event)

    def getTotalWLT(self, year=None, eventcode=None): #returns (w, l, t)
        if eventcode != None:
            events = [eventcode]
        else:
            events = [event for event in self.event_wlt]
            if year != None:
                events = [event for event in events if event[:4] == str(year)]
        w = 0
        l = 0
        t = 0
        for event in events:
            w += self.event_wlt[event][0]
            l += self.event_wlt[event][1]
            t += self.event_wlt[event][2]
        return (w, l, t)

    def getAttr(self, key):
        return self.attrs[key] if key in self.attrs else None

    def __str__(self):
        return "frcpy_frc" + str(self.team_number)

class Match:
    def __init__(self):
        self.red_teams = [] #team_keys
        self.blue_teams = [] #team_keys
        self.finished = False
        # used for discovery
        self.attrs = {}

    def loadTBAData(self, match_tba_data):
        self.event_key = match_tba_data.event_key
        self.comp_level = match_tba_data.comp_level
        self.match_number = match_tba_data.match_number
        self.set_number = match_tba_data.set_number if self.comp_level in ['qf', 'sf', 'f'] else None
        self.key = match_tba_data.key
        self.predicted_time = match_tba_data.predicted_time
        self.scheduled_time = match_tba_data.time
        self.finished = match_tba_data.winning_alliance in ['red', 'blue'] or match_tba_data.actual_time != None
        self.score_breakdown = match_tba_data.score_breakdown
        if 'alliances' in match_tba_data and all(color in match_tba_data['alliances'] for color in ['red', 'blue']) and all('team_keys' in match_tba_data['alliances'][color] for color in ['red', 'blue']):
            self.red_teams += match_tba_data['alliances']['red']['team_keys']
            self.blue_teams += match_tba_data['alliances']['blue']['team_keys']
        if self.finished:
            self.winning_alliance = match_tba_data.winning_alliance
            if 'alliances' in match_tba_data and all(color in match_tba_data['alliances'] for color in ['red', 'blue']) and all('score' in match_tba_data['alliances'][color] for color in ['red', 'blue']):
                self.blue_score = match_tba_data['alliances']['blue']['score']
                self.red_score = match_tba_data['alliances']['red']['score']
           # if 'alliances' in match_tba_data and all(color in match_tba_data['alliances'] for color in ['red', 'blue']) and all('team_keys' in match_tba_data['alliances'][color] for color in ['red', 'blue']):
            #    self.red_teams += match_tba_data['alliances']['red']['team_keys']
             #   self.blue_teams += match_tba_data['alliances']['blue']['team_keys']

    # returns (red_alliance, blue_alliance)
    # returns ([Team, ...], [Team, ...])
    def getTeamObjects(self, team_dict): #team_list = dict of Team objects
        red_teams = []
        blue_teams = []
        for team in self.red_teams:
            if team in team_dict:
                red_teams.append(team_dict[team])
        for team in self.blue_teams:
            if team in team_dict:
                blue_teams.append(team_dict[team])
        if len(red_teams) != len(self.red_teams) or len(blue_teams) != len(self.blue_teams):
            print("Beware", self.key, "couldn't load team objects correctly.")
        return red_teams, blue_teams

    def getAttr(self, key):
        return self.attrs[key] if key in self.attrs else None

class Alliance:
    def __init__(self, event_key, alliance_obj):
        self.team_keys = alliance_obj["picks"]
        if "status" in alliance_obj and isinstance(alliance_obj["status"],dict):
            self.status = alliance_obj["status"]["status"]
        else:
            self.status = None
        self.event_key = event_key

    def wonEvent(self):
        return self.status == "won"

class Event(Location):
    def __init__(self, key):
        self.key = key
        self.year = int(key[:4])
        self.matches = {} # match key -> match object
        self.teams = [] # team keys
        self.attrs = {}

    def getTeamObjects(self, team_list): #team_list = list of Team objects
        teams = []
        for team_obj in team_list:
            if team_obj.key in self.teams:
                teams.append(team_obj)
        if len(teams) != len(self.teams):
            print("Beware {} couldn't load correct number of teams.".format(self.key))
        return teams

    def loadTBA(self, tba, all_teams):
        self.loadTBAData(tba.event(self.key))
        # update alliances
        if self.hasEventFinished():
            self.updateAlliances(tba)
        else:
            self.alliances = []
        # update matches
        self.updateMatches(tba)
        # bring in team keys
        self.loadTeamKeys(tba)
        # update w/l/t
        for team_key in self.teams:
            if team_key in all_teams:
                all_teams[team_key].loadEventWLT(self)

    def updateAlliances(self, tba):
        self.alliances = []
        try:
            alliances = tba.event_alliances(self.key)
        except TypeError:
            alliances = None
        if alliances == None:
            return
        for alliance in alliances:
            if alliance != None:
                self.alliances.append(Alliance(self.key, alliance))

    def getWinningAlliance(self):
        if self.alliances == None or len(self.alliances) == 0:
            return None
        for alliance in self.alliances:
            if alliance.wonEvent():
                return alliance
        return None

    def updateMatches(self, tba):
        for match in tba.event_matches(self.key):
            match_obj = self.matches[match.key] if match.key in self.matches else Match()
            match_obj.loadTBAData(match)
            self.matches[match_obj.key] = match_obj

    def loadTBAData(self, event_tba_data):
        self.key = event_tba_data.key
        self.name = event_tba_data.name
        self.event_code = event_tba_data.event_code
        self.event_type = event_tba_data.event_type
        self.city = event_tba_data.city
        self.state = event_tba_data.state_prov
        self.country = event_tba_data.country
        self.start_date = event_tba_data.start_date
        self.end_date = event_tba_data.end_date
        self.year = event_tba_data.year
        self.short_name = event_tba_data.short_name
        self.event_type_string = event_tba_data.event_type_string
        self.week = event_tba_data.week
        self.location_name = event_tba_data.location_name
        self.playoff_type = event_tba_data.playoff_type
        self.playoff_type_string = event_tba_data.playoff_type_string

    def loadTeamKeys(self, tba):
        self.teams = tba.event_teams(self.key, keys=True)

    def hasEventStarted(self):
        return datetime.today().strftime('%Y-%m-%d') >= self.start_date

    def isEventGoingOn(self):
        return self.hasEventStarted() and not self.hasEventFinished()

    def hasEventFinished(self):
        return datetime.today().strftime('%Y-%m-%d') > self.end_date

    def isOfficial(self):
        return self.event_type <= 6

    def __str__(self):
        return "frcpy_" + str(self.key)

    def getAttr(self, key):
        return self.attrs[key] if key in self.attrs else None


# python3

import heapq

def parallel_processing(n, m, data):
    output = []
    threads = [(0, i) for i in range(n)]                   # Inicialize threads ka (brivais laiks, indeks) kortežos
    heapq.heapify(threads)                                 # Konverte listu uz heep

    for i, t in enumerate(data):
        free_time, index = heapq.heappop(threads)          # Atrod threadu ar visagrako brivo laiku
        output.append((index, free_time))
        heapq.heappush(threads, (free_time + t, index))    # Atjaunina threada brivo laiku ar jauno darbu ilgumu

    return output

def main():
    n, m = map(int, input().split())                       # Pirmie divi input
    data = list(map(int, input().split()))                 # Parejais inputs
    result = parallel_processing(n, m, data)
    for index, start_time in result:
        print(index, start_time)

if __name__ == "__main__":
    main()


import openml
import numpy as np
from app.neo4j.openml_model import Dataset, Task, Flow, Run, graph
from itertools import combinations
import math

print(graph)

def compare_dataset(d1, d2):
    d_1 = openml.datasets.get_dataset(d1)
    d_2 = openml.datasets.get_dataset(d2)
    mf_1 = d_1.qualities
    mf_2 = d_2.qualities
    norm = []
    mf = list(set(mf_1).intersection(mf_2))

    for f in mf:
        if not math.isnan(mf_1[f]) and not math.isnan(mf_2[f]):
            norm.append(mf_1[f] - mf_2[f])

    norm = np.array(norm, dtype='float64')
    return np.linalg.norm(norm)

def get_datasets(limit):
    datasets = openml.datasets.list_datasets(size=limit)
    return [dataset[1] for dataset in  list(datasets.items())]

def get_pairs(datasets):
    pairs = combinations(datasets, 2)
    return list(pairs)

def get_tasks(did):
    tasks = openml.tasks.list_tasks(data_id=did)
    return [task[1] for task in list(tasks.items())]

def get_flows(offset):
    flows = openml.flows.list_flows(offset=offset)
    return [flow[1] for flow in list(flows.items())]

def get_runs(tid):
    runs = openml.runs.list_runs(task=[tid])
    return runs

def populate(limit):

    datasets = get_datasets(limit)
    pairs = get_pairs(datasets)

    for pair in pairs:
        d1 = pair[0]
        d2 = pair[1]

        if Dataset(did=d1['did']).fetch() != None \
            and Dataset(did=d2['did']).fetch() != None:

            print(f"Datasets {d1['name']} and {d2['name']} already in database.")
            continue
        else:
            distance = compare_dataset(d1, d2)

            print(f"Distance between {d1['name']} and {d2['name']} is {distance}.")

            dataset_1 = Dataset(did=d1['did'],
                                name=d1['name'],
                                file_format=d1['format'])
            dataset_2 = Dataset(did=d2['did'],
                                name=d2['name'],
                                file_format=d2['format'])
            dataset_1.save()
            dataset_2.save()
            dataset_1.add_connections(dataset_2, distance)

def populate_datasets(limit):

    datasets = get_datasets(limit)

    for dataset in datasets:
        datasets = get_datasets(limit)
        current = list(Dataset().all)
        dataset_obj = Dataset(did=dataset['did']).fetch()
        if dataset_obj in current:
            connections = dataset_obj.get_connections()
            others = current[:]
            others.remove(dataset_obj)
            unconnected = list(set(others) - set(connections))
            if len(unconnected) > 1:
                for to_connect in unconnected:
                    print(f"Connecting {to_connect} to {dataset_obj}.")
                    distance = compare_dataset(dataset['did'], to_connect.did)
                    dataset_obj.add_connections(to_connect, distance)
                    dataset_obj.save()
            else:
                print(f"Dataset {dataset_obj} is fully connected.")
        else:
            new = Dataset(
                did=dataset['did'],
                name=dataset['name'],
                file_format=dataset['format'],
            )
            print(f"Created new {new}.")
            new.save()
            for to_connect in current:
                    print(f"Connecting {to_connect} to {new}.")
                    distance = compare_dataset(dataset['did'], to_connect.did)
                    new.add_connections(new, distance)
                    new.save()

def populate_tasks():

    datasets = list(Dataset().all)

    for dataset in datasets:
        current = dataset.get_tasks()
        print(f"On dataset {dataset}")
        new = get_tasks(dataset.did)
        for new_task in new:
            task_obj = Task(tid=new_task['tid']).fetch()
            if task_obj not in current:
                task_obj = Task(
                    tid=new_task['tid'],
                    task_type=new_task['task_type'],
                    task_type_id=new_task['ttid'],
                )
                for key, value in new_task.items():
                    if hasattr(task_obj, key):
                        setattr(task_obj, key, value)
                task_obj.save()
                print(f"Adding new task {task_obj}")
                dataset.add_task(task_obj)

# def populate_flows(offset):
#     flows = get_tasks(offset)
#     for flow in flows:
#         f = flows.get_flow(flow['flow_id'])
#         ti =
#     pass

populate_datasets(50)


import logging

from stonkmaster.commands.base import BaseCommand
from stonkmaster.core.language import get_text
from stonkmaster.core.market import is_market_closed, get_info

class PriceCommand(BaseCommand):

    async def execute(self, ctx, ticker):
        try:
            info = get_info(ticker)

            if len(info) <= 1:
                logging.info(f"{ctx.author.display_name} tried to fetch price for invalid ticker {ticker}")
                await ctx.send(get_text("TickerNotFound", self.config).format(ticker.upper(),
                                                                              self.config['emojis']['NotFound']))
                return

            current = info['regularMarketPrice']
            previous = info['previousClose']
            symbol = info['symbol']
            change = ((current - previous) / previous) * 100
            emoji = self.config['emojis']['StockUp'] if change >= 0 else self.config['emojis']['StockDown']

            if 'longName' in info:
                msg = (f"The market price of **{info['longName']} ({symbol})** is **{round(current, 2)}$** "
                       f"({'{0:+.2f}'.format(change)}%)  {emoji}")
            else:
                msg = (f"The market price of **{symbol}** is **{round(current, 2)}$** "
                       f"({'{0:+.2f}'.format(change)}%)  {emoji}")

            logging.info(f"{ctx.author.display_name} fetched price for ticker {symbol} (current={current}, " +
                         f"previous={previous}, change={change}%)")
            await ctx.send(msg)

            if is_market_closed():
                await ctx.send(f"Market is currently **closed** {self.config['emojis']['Closed']}")
            elif symbol == 'GME':
                await ctx.send("Wennst ned woasd, wannst GME vakaffa wuisd, kosd de do orientiern: " +
                               f"<https://gmefloor.com/> {self.config['emojis']['Money']}")
                await ctx.send("Weitere Infos findst do: <https://gme.crazyawesomecompany.com/> " +
                               f"{self.config['emojis']['Bulb']}")

        except Exception as ex:
            logging.exception(f"Exception in PriceCommand: {ex}")
            await ctx.send(get_text("ErrorMsg", self.config).format(self.config['emojis']['Error']))


import tkinter as tk
import numpy as np
import random
import time
import datetime
import threading

def tick():

    time2=time.strftime('%H:%M:%S')
    clock.config(text=time2)
    clock.after(200,tick)

def get_data():
    threading.Timer(5, get_data).start()
    x=np.random.randint(0,40,1)
    print(x[0])
    l_display.config(text = x[0])
    return x[0]

mainwindow = tk.Tk()
mainwindow.geometry('640x340')
mainwindow.title("Sensor Data Live Feed ")

clock=tk.Label(mainwindow,font=("Arial",30), bg='green',fg="white")
clock.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")

l_m=tk.Label(mainwindow,text="Sensor Data ",font=("Arial",30),fg="Black")
l_m.grid(row=0,column=1, padx=10, pady=10, sticky="nsew")

l_t=tk.Label(mainwindow, text="Temperature C",font=("Arial",25))
l_t.grid(row=1,column=0, padx=10, pady=10, sticky="nsew")

l_display=tk.Label(mainwindow,font=("Arial",25),fg="red")
l_display.grid(row=1,column=1, padx=10, pady=10, sticky="nsew")

tick()
get_data()

mainwindow.mainloop()


import sys
n,k=list(map(int,sys.stdin.readline().strip().split()))
things=[]
for _ in range(n):
    line=list(map(int,sys.stdin.readline().strip().split()))
    things.append(line)
def perfact(i,j):
    ans = True
    for index in range(1,k):
        if things[i][index]+things[j][index]==things[i][index-1]+things[j][index-1]:
            continue
        ans=False
        break
    return ans
result=0
for i in range(n):
    for j in range(i+1,n):
        if perfact(i,j):
            result+=1
print(result)


import json
import pyautogui
import time
from TwitchWebsocket import TwitchWebsocket
from handler import *

# https://github.com/CubieDev/TwitchWebsocket

def presshold(key):
    set_given(num=key)

class Settings:
    def __init__(self, bot):
        try:
            # Try to load the file using json.
            # And pass the data to the MyBot class instance if this succeeds.
            with open("settings.txt", "r") as f:
                settings = f.read()
                data = json.loads(settings)
                bot.set_settings(data['Host'],
                                 data['Port'],
                                 data['Channel'],
                                 data['Nickname'],
                                 data['Authentication'])
        except ValueError:
            raise ValueError("Error in settings file.")
        except FileNotFoundError:
            # If the file is missing, create a standardised settings.txt file
            # With all parameters required.
            with open('settings.txt', 'w') as f:
                standard_dict = {
                    "Host": "irc.chat.twitch.tv",
                    "Port": 6667,
                    "Channel": "#<channel>",
                    "Nickname": "<name>",
                    "Authentication": "oauth:<auth>"
                }
                f.write(json.dumps(standard_dict, indent=4, separators=(',', ': ')))
                raise ValueError("Please fix your settings.txt file that was just generated.")

class MyBot:
    def __init__(self):
        self.host = None
        self.port = None
        self.chan = None
        self.nick = None
        self.auth = None

        # Fill previously initialised variables with data from the settings.txt file
        Settings(self)

        self.ws = TwitchWebsocket(host=self.host,
                                  port=self.port,
                                  chan=self.chan,
                                  nick=self.nick,
                                  auth=self.auth,
                                  callback=self.message_handler,
                                  capability=["membership", "tags", "commands"],
                                  live=False)
        self.ws.start_blocking()

    def set_settings(self, host, port, chan, nick, auth):
        self.host = host
        self.port = port
        self.chan = chan
        self.nick = nick
        self.auth = auth

    def message_handler(self, m):
        if m.type == "PRIVMSG":
            pass
        msg = m.message
        print(m.user, ":", msg)
        if msg == "1" or msg == "!place 1":
            presshold("1")
        if msg == "2" or msg == "!place 2":
            presshold("2")
        if msg == "3" or msg == "!place 3":
            presshold("3")
        if msg == "4" or msg == "!place 4":
            presshold("4")
        if msg == "5" or msg == "!place 5":
            presshold("5")
        if msg == "6" or msg == "!place 6":
            presshold("6")
        if msg == "7" or msg == "!place 7":
            presshold("7")
        if msg == "8" or msg == "!place 8":
            presshold("8")
        if msg == "9" or msg == "!place 9":
            presshold("9")

if __name__ == "__main__":
    MyBot()


import os
import sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
sys.path.append('G:\Work\python\JTDI\mysite\settings.py')

import datetime

from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.db.models import Q
from django.shortcuts import redirect

from JtdiTASKS.models import Task

def send_digest():
    users = User.objects.filter(email__exact='')
    for user in users:
        currentdate = datetime.datetime.today()
        start_day = currentdate.combine(currentdate, currentdate.min.time())
        end_day = currentdate.combine(currentdate, currentdate.max.time())
        first_day = datetime.date(1001, 1, 1)

        tasks_overdue = Task.objects.filter(active=True).filter(Q(author=user) | Q(performer=user)) \
            .filter(date_time__range=(first_day, start_day)) \
            .order_by('date', 'priority', 'time')

        tasks_today = Task.objects.filter(active=True).filter(Q(author=user) | Q(performer=user)) \
            .filter(date_time__range=(start_day, end_day)) \
            .order_by('date', 'priority', 'time')
        body_mail = '
 Задачи на сегодня
'
        for task in tasks_today:
            body_mail = body_mail + '\n' + task.title + ''

        body_mail = body_mail + '
 Просроченые задачи
'
        for task in tasks_overdue:
            body_mail = body_mail + '\n' + task.title + ''

        send_mail('Дайджест задач', body_mail, settings.EMAIL_HOST_USER, [user.email])

send_digest()


# -*- coding: utf-8 -*-

from itertools import accumulate
from operator import xor
from typing import List

class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
        prefix_xors = list(accumulate([0] + arr, xor))
        return [prefix_xors[j + 1] ^ prefix_xors[i] for i, j in queries]

if __name__ == "__main__":
    solution = Solution()

    assert [2, 7, 14, 8] == solution.xorQueries(
        [1, 3, 4, 8], [[0, 1], [1, 2], [0, 3], [3, 3]]
    )
    assert [8, 0, 4, 4] == solution.xorQueries(
        [4, 8, 2, 10], [[2, 3], [1, 3], [0, 0], [0, 3]]
    )


from django.urls import path
from computer.views import ComputerList,ComputerCreate,ComputerDetail,ComputerDelete,ComputerInfoUpdate,Thanks,ComputerSpecificationView,ComputerBrandView,ComputerSpecification_Opt,upload_image
urlpatterns = [
    path('',ComputerList.as_view(),name='computerlist'),
    path('createlist/',ComputerCreate.as_view(),name='computercreate'),
    path('computerdetail/<int:id>',ComputerDetail.as_view(),name='computerdetail'),
    path('computerdelete/<int:id>', ComputerDelete.as_view(), name="computerdelete"),
    path('computerinfoupdate/<int:id>',ComputerInfoUpdate.as_view(),name='computerupdate'),
    path('thanks/',Thanks.as_view(),name='thanks'),
    path('computerspecificationform/',ComputerSpecificationView.as_view(),name="computerspecificationform"),
    path('computerbrandform/',ComputerBrandView.as_view(),name='computerbrandform'),
    path('computerspecificationopt/',ComputerSpecification_Opt.as_view(),name='ComputerSpecification_Opt'),
    path('img/',upload_image.as_view(),name='images'),
    # path('image',image.as_view(),name='image'),
]


import sys, pygame
from pipe import Pipe, PipeManager
from floor import Floor
from sound import Sound
from score import Score
from mon import Mon

# hàm trò chơi
pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512)
pygame.init()
idx = 0
# đặt size cho cửa sổ
WIN = pygame.display.set_mode((360, 640))

# set up opening
opening = pygame.image.load('image/opening .png').convert()

# set up background
bg = pygame.image.load('image/background.png').convert()

# đặt tên cửa sổ
pygame.display.set_caption("FLAPPY MON")

# xác định số frame mỗi giây
FPS = 60  # tốc dộ bình thường của game
clock = pygame.time.Clock()
# thêm ống
PIPE_SURFACE = pygame.image.load('image/column.png').convert()
PIPE_HEIGHT = [i for i in range(300, 500)]
# thêm font chữ
game_font = pygame.font.Font('Audiowide-Regular (1).ttf', 40)
# biến
game_active = True
# điểm
score = Score(WIN=WIN, game_font=game_font)
doramon = Mon()
floor = Floor(WIN=WIN)
sound = Sound()
pipe = Pipe(PIPE_SURFACE=PIPE_SURFACE, PIPE_HEIGHT=PIPE_HEIGHT)
pipe_manager = PipeManager(WIN=WIN, sound=sound, score=score, idx=idx, game_active=game_active, PIPE_HEIGHT=PIPE_HEIGHT, PIPE_SURFACE=PIPE_SURFACE)

# tạo màn hình kết thúc
game_over_surface = pygame.image.load('image/opening .png').convert_alpha()
game_over_rect = game_over_surface.get_rect(center=(180, 320))
# tạo timer
spawnpipe = pygame.USEREVENT
pygame.time.set_timer(spawnpipe, 1200)  # sau 1.2s tạo ra ống mới

def check_collision(pipes):  # check va chạm
    for pipee in pipes:
        if doramon.mon_rect.colliderect(pipee):
            sound.hit_sound.play()
            return False
    if doramon.mon_rect.top <= -100 or doramon.mon_rect.bottom >= 550:  # kiểm soát mon không bay ra ngoài cửa sổ
        sound.hit_sound.play()
        return False
    return True

def gameStart(WIN):

    WIN.blit(opening, (0, 0))

    while True:  # tạo loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                return

        pygame.display.update()
        clock.tick(FPS)

def main(game_active):

    while True:  # tạo loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and game_active: #Tạo hiệu ứng bay
                    # jump
                    doramon.set_mon_movement(-5)
                    sound.flap_sound.play()
                if event.key == pygame.K_SPACE and game_active == False: #tạo di chuyển của ống
                    game_active = True
                    pipe_manager.clear_pipe_list()
                    doramon.mon_rect.center = (100, 320)
                    doramon.set_mon_movement(0)
                    score.reset_score()
                    pipe_manager.idx = 0
            if event.type == spawnpipe: #tạo hệ thống ống
                pipe_pos = pipe.create_pipe()
                pipe_manager.add_pipe(pipe_pos)

        if game_active:
            WIN.blit(bg, (0, 0))  # thêm background
            doramon.move()
            WIN.blit(doramon.rotated_mon, doramon.mon_rect)  # thêm mon vào
            # ống
            pipe_manager.pipe_movement()
            pipe_manager.draw_pipe()
            game_active = check_collision(pipe_manager.get_pipe_list())
            # điểm
            score.display_score('main game')
            floor.move_floor()
            floor.draw_floor()
            floor.check_and_reset_floor()
        else:
            # màn hình game over
            WIN.blit(game_over_surface, game_over_rect)
            # điểm
            score.update_score()
            score.display_score('game over')
        #  thêm floor chuyển động
        #floor.move_floor()
        floor.draw_floor()
        #floor.check_and_reset_floor()

        pygame.display.update()
        clock.tick(FPS)  # để kiểm soát tốc độ của chương trình

if __name__ == '__main__':
    gameStart(WIN)
    main(game_active)


import enum
import json

from .base_client import BaseClient

class ApiPaths(enum.Enum):
    """ Enumeration of api paths.

    This implementation assumes that the endpoint for shipyard
    includes api/v1.0, so it is not repeated here.
    """
    _BASE_URL = '{}/'
    GET_CONFIGDOCS = _BASE_URL + 'configdocs'
    POST_GET_CONFIG = _BASE_URL + 'configdocs/{}'
    GET_RENDERED = _BASE_URL + 'renderedconfigdocs'
    COMMIT_CONFIG = _BASE_URL + 'commitconfigdocs'
    POST_GET_ACTIONS = _BASE_URL + 'actions'
    GET_ACTION_DETAIL = _BASE_URL + 'actions/{}'
    GET_VALIDATION_DETAIL = _BASE_URL + 'actions/{}/validations/{}'
    GET_STEP_DETAIL = _BASE_URL + 'actions/{}/steps/{}'
    GET_STEP_LOG = _BASE_URL + 'actions/{}/steps/{}/logs'
    POST_CONTROL_ACTION = _BASE_URL + 'actions/{}/control/{}'
    GET_NOTEDETAILS = _BASE_URL + 'notedetails/{}'
    GET_WORKFLOWS = _BASE_URL + 'workflows'
    GET_DAG_DETAIL = _BASE_URL + 'workflows/{}'
    GET_SITE_STATUSES = _BASE_URL + 'site_statuses'

class ShipyardClient(BaseClient):
    """
    A client for shipyard API
    :param context: shipyardclient_context, context object
    """
    # Set up the values used to look up the service endpoint.
    interface = 'public'
    service_type = 'shipyard'

    def post_configdocs(self,
                        collection_id=None,
                        buffer_mode='rejectoncontents',
                        empty_collection=False,
                        document_data=None):
        """
        Ingests a collection of documents
        :param str collection_id: identifies a collection of docs.Bucket_id
        :param str buffermode: append|replace|rejectOnContents
        :param empty_collection: True if the collection is empty. Document
            data will be ignored if this flag is set to True. Default: False
        :param str document_data: data in a format understood by Deckhand(YAML)
        :returns: diff from last committed revision to new revision
        :rtype: Response object
        """
        query_params = {"buffermode": buffer_mode}
        if empty_collection:
            query_params['empty-collection'] = True
        url = ApiPaths.POST_GET_CONFIG.value.format(
            self.get_endpoint(),
            collection_id
        )
        return self.post_resp(url, query_params, document_data)

    def get_configdocs(self, collection_id=None, version='buffer',
                       cleartext_secrets=False):
        """
        Get the collection of documents from deckhand specified by
        collection id
        :param collection_id: String, bucket_id in deckhand
        :param version: String, buffer|committed|last_site_action|
                                successful_site_action
        :rtype: Response object
        """
        query_params = {"version": version}
        if cleartext_secrets is True:
            query_params['cleartext-secrets'] = 'true'
        url = ApiPaths.POST_GET_CONFIG.value.format(
            self.get_endpoint(),
            collection_id)
        return self.get_resp(url, query_params)

    def get_configdocs_status(self, versions=None):
        """
        Get the status of the collection of documents from shipyard
        :returns: Response object
        :param versions: List of versions to compare
        """
        query_params = {"versions": versions}
        url = ApiPaths.GET_CONFIGDOCS.value.format(self.get_endpoint())
        return self.get_resp(url, query_params)

    def get_rendereddocs(self, version='buffer', cleartext_secrets=False):
        """
        :param str version: committed|buffer|last_site_action|
                            successful_site_action
        :returns: full set of configdocs in their rendered form.
        :rtype: Response object
        """
        query_params = {"version": version}
        if cleartext_secrets is True:
            query_params['cleartext-secrets'] = 'true'
        url = ApiPaths.GET_RENDERED.value.format(
            self.get_endpoint()
        )
        return self.get_resp(url, query_params)

    def commit_configdocs(self, force=False, dryrun=False):
        """
        :param force: boolean, True|False
        :param dryrun: boolean, True|False
        :returns: dictionary, validations from Airship components
        :rtype: Response object
        """
        query_params = {"force": force, "dryrun": dryrun}
        url = ApiPaths.COMMIT_CONFIG.value.format(self.get_endpoint())
        return self.post_resp(url, query_params)

    def get_actions(self):
        """
        A list of actions that have been executed through shipyard's action API
        :returns: lists all actions
        :rtype: Response object
        """
        url = ApiPaths.POST_GET_ACTIONS.value.format(
            self.get_endpoint()
        )
        return self.get_resp(url)

    def post_actions(self, name=None, parameters=None,
                     allow_intermediate_commits=False):
        """
        Creates an action in the system. This will cause some action to start.
        :param str name: name of supported action to invoke
        :param dict parameters: parameters to use for trigger invocation
        :param allow_intermediate_commits: boolean, True|False
        :returns: action entity created successfully
        :rtype: Response object
        """
        query_params = (
            {"allow-intermediate-commits": allow_intermediate_commits})
        action_data = {"name": name, "parameters": parameters}
        url = ApiPaths.POST_GET_ACTIONS.value.format(
            self.get_endpoint()
        )
        return self.post_resp(url=url,
                              query_params=query_params,
                              data=json.dumps(action_data),
                              content_type='application/json')

    def get_action_detail(self, action_id=None):
        """
        Used to get details about an action
        :param str action_id: Unique ID for a particular action
        :returns: information describing the action
        :rtype: Response object
        """
        url = ApiPaths.GET_ACTION_DETAIL.value.format(
            self.get_endpoint(),
            action_id
        )
        return self.get_resp(url)

    def get_validation_detail(self, action_id=None, validation_id=None):
        """
        Allows for drilldown to validation detailed info.
        :param str action_id: Unique action id
        :param str validation_id: id of the validation
        :returns: validation details about action
        :rtype: Response object
        """
        url = ApiPaths.GET_VALIDATION_DETAIL.value.format(
            self.get_endpoint(), action_id, validation_id)
        return self.get_resp(url)

    def get_step_detail(self, action_id=None, step_id=None):
        """
        Allow for drilldown to step information
        :param str action_id: Unique action id
        :param str step_id: step id
        :returns: details for a step by id for the given action by Id
        :rtype: Response object
        """
        url = ApiPaths.GET_STEP_DETAIL.value.format(
            self.get_endpoint(),
            action_id,
            step_id
        )
        return self.get_resp(url)

    def get_step_log(self, action_id=None, step_id=None, try_number=None):
        """
        Retrieve logs for a particular step
        :param str action_id: Unique action id
        :param str step_id: step id
        :param int try_number: The logs that user wants to retrieve. Note that
                               a workflow can retry multiple times with the
                               names of the logs as 1.log, 2.log, 3.log, etc.
                               Logs from the last attempt will be returned if
                               'try' is not specified.
        :returns: Logs for the step
        :rtype: Response object
        """
        if try_number:
            query_params = {'try': try_number}
        else:
            query_params = {}

        url = ApiPaths.GET_STEP_LOG.value.format(
            self.get_endpoint(),
            action_id,
            step_id
        )
        return self.get_resp(url, query_params)

    def post_control_action(self, action_id=None, control_verb=None):
        """
        Allows for issuing DAG controls against an action.
        :param str action_id: Unique action id
        :param str control_verb: control action to be taken against an activity
        :returns: containing the status of the action fail or success
        :rtype: Response object
        """
        url = ApiPaths.POST_CONTROL_ACTION.value.format(
            self.get_endpoint(), action_id, control_verb)
        return self.post_resp(url)

    def get_note_details(self, note_id):
        """Retrieve note details from a note's associated information

        :param note_id: The ID of the note having additional information
        """
        url = ApiPaths.GET_NOTEDETAILS.value.format(
            self.get_endpoint(), note_id)
        return self.get_resp(url)

    def get_workflows(self, since=None):
        """
        Queries airflow for DAGs that are running or have run
        (successfully or unsuccessfully)
        :param str since: iso8601 date optional
        :returns: DAGS running or that have run
        :rtype: Response object
        """
        query_params = {'since': since}
        url = ApiPaths.GET_WORKFLOWS.value.format(self.get_endpoint())
        return self.get_resp(url, query_params)

    def get_dag_detail(self, workflow_id=None):
        """
        details of a particular scheduled DAG's output
        :param str workflow_id: unique id for a DAG
        :returns: details of a DAGs output
        :rtype: Response object
        """
        url = ApiPaths.GET_DAG_DETAIL.value.format(self.get_endpoint(),
                                                   workflow_id)
        return self.get_resp(url)

    def get_site_statuses(self, fltrs=None):
        """
        Get statuses for the site.
        :param str filters: status-types for site statuses to retrieve.
        :rtype: Response object
        """
        if fltrs:
            query_params = {'filters': fltrs}
        else:
            query_params = {}

        url = ApiPaths.GET_SITE_STATUSES.value.format(
            self.get_endpoint())
        return self.get_resp(url, query_params)


from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Firefox()  # can be webdriver.PhantomJS()
browser.get('https://www.woolworths.com.au/shop/browse/specials/half-price')
#browser.get('https://www.woolworths.com.au/shop/browse/specials/half-price/bakery')
# wait for the select element to become visible
#page = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.selectedFilters-count")))
page = WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.tileList-tiles")))
item_list_element = page.find_elements_by_css_selector(".shelfProductTile-content")
#36
for div_element in item_list_element:
    print(div_element)
    title = div_element.find_element_by_class_name("shelfProductTile-descriptionLink")
    print(title.text)
    try:
        priceDollars = div_element.find_element_by_class_name("price-dollars")
        priceCents = div_element.find_element_by_class_name("price-cents")
        wasPrice = div_element.find_element_by_class_name("shelfProductTile-wasPrice")
        print(priceDollars.text)
        print(priceCents.text)
        print(wasPrice.text)
    except NoSuchElementException:
        print("OUT OF STOCK")

    #select = Select(select_element)
    #for option in select.options[1:]:
    #    print(option.text)

    # browser.quit()


import turtle
import pandas

from turtle import Turtle
screen = turtle.Screen()
screen.title("U.S. States Game")
image = "blank_states_img.gif"
screen.addshape(image)
turtle.shape(image)
state = Turtle()
state.hideturtle()
state.penup()
data = pandas.read_csv("50_states.csv")
states_as_list = data.state.to_list()
correct_states = []
missing_states = []
total_states = 0
game_is_on = True
while game_is_on:
    answer_state = screen.textinput(title=f"{total_states}/50 Guess the State", prompt="What's another state's name?").title()
    if answer_state == "Exit":
        game_is_on = True
        for state in states_as_list:
            if state not in correct_states:
                missing_states.append(state)
        new_data = pandas.DataFrame(missing_states)
        new_data.to_csv("states_to_learn.csv")
        break
    if answer_state in states_as_list:
        if answer_state not in correct_states:
            correct_states.append(answer_state)
            total_states += 1
            answer_data = data[data.state == answer_state]
            x_coord = int(answer_data.x)
            y_coord = int(answer_data.y)
            state.goto(x_coord, y_coord)
            state.write(answer_state)
            if total_states == 50:
                game_is_on = True

100 Days of Code/2. Intermediate [15-31]/Day 25 US Quiz /main.py


from tkinter.filedialog import askopenfilename
import pandas as pd
import numpy as np
import engine_calculations_helper as ech

input_filename = askopenfilename()
input_dataframe = pd.read_csv(input_filename)

dynamo_arm_length = input_dataframe['dynamo_arm_length'][0]

rpm = input_dataframe['rpm']
load = input_dataframe['load']

output_torque = ech.calc_output_torque(load, dynamo_arm_length)
bp = ech.calc_brake_power(output_torque, rpm)

ip = []

for i in range(0, bp.size):
    if i % 2 == 0:
        ip.append(abs(bp[i] - bp[i+1]) / 1000)  # W -> kW
    else:
        ip.append(0)

input_dataframe['ip1'] = np.array(ip)

output_filename = input_filename[0: input_filename.rfind('/')] \
                  + '/Outputs/output_' \
                  + input_filename[input_filename.rfind('/') + 1:]

input_dataframe.to_csv(output_filename)


class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        d = Counter(nums)
        heap = [(-x[1], x[0]) for x in d.items()]
        heapify(heap)
        ans = []

        while len(ans) < k:
            ans.append(heappop(heap)[1])

        return ans


'''
Implement a URL shortener with the following methods:

    shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl.
    restore(short), which expands the shortened string into the original url. If no such shortened string exists, return null.

Hint: What if we enter the same URL twice?
'''

from hashlib import sha256 # Can use any hash, but this will do.

class URLShortener:
    def __init__(self):
        self._char_map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # Length: 10+26+26 = 62
        self.url_map = dict()

    def shorten(self, url: str):
        # Start by getting an integer from a sha256 hash of the URL.
        n = int(sha256(url.encode()).hexdigest(), 16)
        # Converting the hashed value to a 62-bit alphanumeric value.
        full_short_url = ""
        while n > 0:
            map_key = n % 62
            full_short_url += self._char_map[map_key]
            n //= 62
        # Now shorten the URL. Start with 6 characters. Add one character if there is a clash.
        total_chars = 6
        while full_short_url[:total_chars] in self.url_map and total_chars < len(full_short_url): # Edge case: Total hash clash. Odds of occurrence are 1 in 2^256.
            # Case - URL was already shortened. No need to add it again.
            if self.url_map[full_short_url[:total_chars]] == url:
                break
            total_chars += 1

        self.url_map[full_short_url[:total_chars]] = url
        return full_short_url[:total_chars]

    def restore(self, short: str):
        if short in self.url_map:
            return self.url_map[short]
        return None

if __name__ == "__main__":
    s = URLShortener()
    short1 = s.shorten("https://www.google.com/")
    restored1 = s.restore(short1)
    print(short1, restored1)
    short2 = s.shorten("https://www.superduperlong.com/kg2vghv2vgf2kvv2gfg2hkvg22fvg2kv2kfv2k3jf2v2vgc")
    restored2 = s.restore(short2)
    print(short2, restored2)


import os
import math
from itertools import chain

# TEST_MODE = True
TEST_MODE = False
NUM_OF_TEST = 3

def convolution(image, filt, stride=(1, 1), padding=(0, 0), bias=0):
    f_x, f_y = len(filt), len(filt[0])

    if padding == 'same' or padding == 'SAME':
        p_x = int((f_x - 1) / 2)
        p_y = int((f_y - 1) / 2)
    else:
        p_x, p_y = padding

    s_x, s_y = stride

    image_x = len(image)
    image_y = len(image[0])

    padded_len_x = image_x + 2 * p_x
    padded_len_y = image_y + 2 * p_y

    out_x = math.floor((padded_len_x - f_x) / s_x + 1)
    out_y = math.floor((padded_len_y - f_y) / s_y + 1)
    out = [[0] * out_y for _ in range(out_x)]

    image_padded = [[0] * padded_len_y for _ in range(padded_len_x)]

    for i in range(image_x):
        image_padded[i + p_x][p_y:p_y + image_y] = image[i]

    for i in range(out_x):
        x = i * s_x
        for j in range(out_y):
            y = j * s_y
            # sub_M = M[i:i+p, j:j+q] -- 2D slicing in native python list
            sub_M = [image_padded[_][y:y + f_y] for _ in range(x, x + f_x)]
            out[i][j] = sum(sub_M[_i][_j] * filt[_i][_j] for _i in range(f_x) for _j in range(f_y)) + bias

    return out

def solver(input):
    filter = [
        [-1/9, -1/9, -1/9],
        [-1/9, 8/9, -1/9],
        [-1/9, -1/9, -1/9]
    ]

    m, n = map(int , input().split())
    mat = []
    for i in range(m):
        mat.append(list(map(int , input().split())))
    # print(mat)
    conv = convolution(mat, filter, padding="same")

    for row in conv:
        print(' '.join(map(str, map(int, row))))
    # print(conv)

if __name__ == '__main__':
    if TEST_MODE:
        for i in range(1, NUM_OF_TEST + 1):
            print(f'----------\nTestCase {i}')
            with open('./testcase/samples-{}/{}.in'.format(os.path.basename(__file__).replace('.py', ''), i)) as f: content = f.readlines()
            holder = (_.strip() for _ in content)
            solver(lambda: next(holder))
    else:
        solver(input)

FPT University - Hackathon 2021 - Round 2/A.py


__ver_major__ = 0
__ver_minor__ = 2
__ver_patch__ = 0
__ver_sub__ = ""
__version__ = "%d.%d.%d%s" % (__ver_major__,__ver_minor__,__ver_patch__,__ver_sub__)

from collections import deque

def dumps(value,encoding=None):
    """dumps(object,encoding=None) -> string

    This function dumps a python object as a tnetstring.
    """
    #  This uses a deque to collect output fragments in reverse order,
    #  then joins them together at the end.  It's measurably faster
    #  than creating all the intermediate strings.
    #  If you're reading this to get a handle on the tnetstring format,
    #  consider the _gdumps() function instead; it's a standard top-down
    #  generator that's simpler to understand but much less efficient.
    q = deque()
    _rdumpq(q,0,value,encoding)
    return "".join(q)

def dump(value,file,encoding=None):
    """dump(object,file,encoding=None)

    This function dumps a python object as a tnetstring and writes it to
    the given file.
    """
    file.write(dumps(value,encoding))
    file.flush()

def _rdumpq(q,size,value,encoding=None):
    """Dump value as a tnetstring, to a deque instance, last chunks first.

    This function generates the tnetstring representation of the given value,
    pushing chunks of the output onto the given deque instance.  It pushes
    the last chunk first, then recursively generates more chunks.

    When passed in the current size of the string in the queue, it will return
    the new size of the string in the queue.

    Operating last-chunk-first makes it easy to calculate the size written
    for recursive structures without having to build their representation as
    a string.  This is measurably faster than generating the intermediate
    strings, especially on deeply nested structures.
    """
    write = q.appendleft
    if value is None:
        write("0:~")
        return size + 3
    if value is True:
        write("4:true!")
        return size + 7
    if value is False:
        write("5:false!")
        return size + 8
    if isinstance(value,(int,long)):
        data = str(value)
        ldata = len(data)
        span = str(ldata)
        write("#")
        write(data)
        write(":")
        write(span)
        return size + 2 + len(span) + ldata
    if isinstance(value,(float,)):
        #  Use repr() for float rather than str().
        #  It round-trips more accurately.
        #  Probably unnecessary in later python versions that
        #  use David Gay's ftoa routines.
        data = repr(value)
        ldata = len(data)
        span = str(ldata)
        write("^")
        write(data)
        write(":")
        write(span)
        return size + 2 + len(span) + ldata
    if isinstance(value,str):
        lvalue = len(value)
        span = str(lvalue)
        write(",")
        write(value)
        write(":")
        write(span)
        return size + 2 + len(span) + lvalue
    if isinstance(value,(list,tuple,)):
        write("]")
        init_size = size = size + 1
        for item in reversed(value):
            size = _rdumpq(q,size,item,encoding)
        span = str(size - init_size)
        write(":")
        write(span)
        return size + 1 + len(span)
    if isinstance(value,dict):
        write("}")
        init_size = size = size + 1
        for (k,v) in value.iteritems():
            size = _rdumpq(q,size,v,encoding)
            size = _rdumpq(q,size,k,encoding)
        span = str(size - init_size)
        write(":")
        write(span)
        return size + 1 + len(span)
    if isinstance(value,unicode):
        if encoding is None:
            raise ValueError("must specify encoding to dump unicode strings")
        value = value.encode(encoding)
        lvalue = len(value)
        span = str(lvalue)
        write(",")
        write(value)
        write(":")
        write(span)
        return size + 2 + len(span) + lvalue
    raise ValueError("unserializable object")

def _gdumps(value,encoding):
    """Generate fragments of value dumped as a tnetstring.

    This is the naive dumping algorithm, implemented as a generator so that
    it's easy to pass to "".join() without building a new list.

    This is mainly here for comparison purposes; the _rdumpq version is
    measurably faster as it doesn't have to build intermediate strins.
    """
    if value is None:
        yield "0:~"
    elif value is True:
        yield "4:true!"
    elif value is False:
        yield "5:false!"
    elif isinstance(value,(int,long)):
        data = str(value)
        yield str(len(data))
        yield ":"
        yield data
        yield "#"
    elif isinstance(value,(float,)):
        data = repr(value)
        yield str(len(data))
        yield ":"
        yield data
        yield "^"
    elif isinstance(value,(str,)):
        yield str(len(value))
        yield ":"
        yield value
        yield ","
    elif isinstance(value,(list,tuple,)):
        sub = []
        for item in value:
            sub.extend(_gdumps(item))
        sub = "".join(sub)
        yield str(len(sub))
        yield ":"
        yield sub
        yield "]"
    elif isinstance(value,(dict,)):
        sub = []
        for (k,v) in value.iteritems():
            sub.extend(_gdumps(k))
            sub.extend(_gdumps(v))
        sub = "".join(sub)
        yield str(len(sub))
        yield ":"
        yield sub
        yield "}"
    elif isinstance(value,(unicode,)):
        if encoding is None:
            raise ValueError("must specify encoding to dump unicode strings")
        value = value.encode(encoding)
        yield str(len(value))
        yield ":"
        yield value
        yield ","
    else:
        raise ValueError("unserializable object")

def loads(string,encoding=None):
    """loads(string,encoding=None) -> object

    This function parses a tnetstring into a python object.
    """
    #  No point duplicating effort here.  In the C-extension version,
    #  loads() is measurably faster then pop() since it can avoid
    #  the overhead of building a second string.
    return pop(string,encoding)[0]

def load(file,encoding=None):
    """load(file,encoding=None) -> object

    This function reads a tnetstring from a file and parses it into a
    python object.  The file must support the read() method, and this
    function promises not to read more data than necessary.
    """
    #  Read the length prefix one char at a time.
    #  Note that the netstring spec explicitly forbids padding zeros.
    c = file.read(1)
    if not c.isdigit():
        raise ValueError("not a tnetstring: missing or invalid length prefix")
    datalen = ord(c) - ord("0")
    c = file.read(1)
    if datalen != 0:
        while c.isdigit():
            datalen = (10 * datalen) + (ord(c) - ord("0"))
            if datalen > 999999999:
                errmsg = "not a tnetstring: absurdly large length prefix"
                raise ValueError(errmsg)
            c = file.read(1)
    if c != ":":
        raise ValueError("not a tnetstring: missing or invalid length prefix")
    #  Now we can read and parse the payload.
    #  This repeats the dispatch logic of pop() so we can avoid
    #  re-constructing the outermost tnetstring.
    data = file.read(datalen)
    if len(data) != datalen:
        raise ValueError("not a tnetstring: length prefix too big")
    type = file.read(1)
    if type == ",":
        if encoding is not None:
            return data.decode(encoding)
        return data
    if type == "#":
        try:
            return int(data)
        except ValueError:
            raise ValueError("not a tnetstring: invalid integer literal")
    if type == "^":
        try:
            return float(data)
        except ValueError:
            raise ValueError("not a tnetstring: invalid float literal")
    if type == "!":
        if data == "true":
            return True
        elif data == "false":
            return False
        else:
            raise ValueError("not a tnetstring: invalid boolean literal")
    if type == "~":
        if data:
            raise ValueError("not a tnetstring: invalid null literal")
        return None
    if type == "]":
        l = []
        while data:
            (item,data) = pop(data,encoding)
            l.append(item)
        return l
    if type == "}":
        d = {}
        while data:
            (key,data) = pop(data,encoding)
            (val,data) = pop(data,encoding)
            d[key] = val
        return d
    raise ValueError("unknown type tag")

def pop(string,encoding=None):
    """pop(string,encoding=None) -> (object, remain)

    This function parses a tnetstring into a python object.
    It returns a tuple giving the parsed object and a string
    containing any unparsed data from the end of the string.
    """
    #  Parse out data length, type and remaining string.
    try:
        (dlen,rest) = string.split(":",1)
        dlen = int(dlen)
    except ValueError:
        raise ValueError("not a tnetstring: missing or invalid length prefix")
    try:
        (data,type,remain) = (rest[:dlen],rest[dlen],rest[dlen+1:])
    except IndexError:
        #  This fires if len(rest) < dlen, meaning we don't need
        #  to further validate that data is the right length.
        raise ValueError("not a tnetstring: invalid length prefix")
    #  Parse the data based on the type tag.
    if type == ",":
        if encoding is not None:
            return (data.decode(encoding),remain)
        return (data,remain)
    if type == "#":
        try:
            return (int(data),remain)
        except ValueError:
            raise ValueError("not a tnetstring: invalid integer literal")
    if type == "^":
        try:
            return (float(data),remain)
        except ValueError:
            raise ValueError("not a tnetstring: invalid float literal")
    if type == "!":
        if data == "true":
            return (True,remain)
        elif data == "false":
            return (False,remain)
        else:
            raise ValueError("not a tnetstring: invalid boolean literal")
    if type == "~":
        if data:
            raise ValueError("not a tnetstring: invalid null literal")
        return (None,remain)
    if type == "]":
        l = []
        while data:
            (item,data) = pop(data,encoding)
            l.append(item)
        return (l,remain)
    if type == "}":
        d = {}
        while data:
            (key,data) = pop(data,encoding)
            (val,data) = pop(data,encoding)
            d[key] = val
        return (d,remain)
    raise ValueError("unknown type tag")


import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import dateutil
import urllib.request
import requests

def obtenerFabricante(macAddress):

    validador = "^(([0-9A-Fa-f]{2}:){5})([0-9A-Fa-f]{2})$"

    peticion = requests.get("http://www.macvendorlookup.com/oui.php?mac={}".format(macAddress), verify=False)
    print(peticion.text + str(peticion.status_code))
    if peticion.status_code != 200 or not(peticion.text):
        return None
    infoJson = peticion.json()
    # print()
    fabricante = infoJson[0]["company"]
    return fabricante

# infoMacAddress = obtenerFabricante("74:AA:FE:A5:7E:90")
# print(infoMacAddress)
# In[55]:
validacionMAC = "^(([0-9A-Fa-f]{2}:){5})([0-9A-Fa-f]{2})$"

dateparse = lambda x: pd.datetime.strptime(x,'%Y-%m-%d %h:%m:%s')
data = pd.read_csv('./tmp/rp_conexion.csv',sep=';',index_col=False, parse_dates={'datetime':['fecha','hora']}, usecols=["codigo","pauta_id","sitio_id","mac_usr","fecha","hora","ip_local","ip_usr","so","navegador","url_ref","tiempo_espera"])

data["filtroMAC"] = data['mac_usr'].str.contains(validacionMAC)
# data = data[filter]

# print(data)

data = data[data["filtroMAC"] == True]

# print(nuevoData)

del data["filtroMAC"]

# data = data[:10000]

# print(len(data))

try:

    data["fabricante-dispositivo"] = data["mac_usr"].apply(obtenerFabricante)

except:

    data.to_csv("dispositivos_fabricantes_excepcion.csv")

finally:

    data.to_csv("dispositivos_fabricantes.csv")

# data.to_csv("dispositivos_fabricantes.csv")

# print(data)

# dispositivos = data.groupby("so").size()
#
# print(dispositivos)