text:
ONE_LOCATION = ENV["ONE_LOCATION"] if !defined?(ONE_LOCATION)

if !ONE_LOCATION
   BIN_LOCATION = "/usr/bin" if !defined?(BIN_LOCATION)
   LIB_LOCATION = "/usr/lib/one" if !defined?(LIB_LOCATION)
   ETC_LOCATION = "/etc/one/" if !defined?(ETC_LOCATION)
   VAR_LOCATION = "/var/lib/one" if !defined?(VAR_LOCATION)
else
   BIN_LOCATION = ONE_LOCATION + "/bin" if !defined?(BIN_LOCATION)
   LIB_LOCATION = ONE_LOCATION + "/lib" if !defined?(LIB_LOCATION)
   ETC_LOCATION = ONE_LOCATION  + "/etc/" if !defined?(ETC_LOCATION)
   VAR_LOCATION = ONE_LOCATION + "/var/" if !defined?(VAR_LOCATION)
end

ENV['LANG'] = 'C'

$: << LIB_LOCATION+'/ruby/vendors/rbvmomi/lib'
$: << LIB_LOCATION+'/ruby'

require 'rbvmomi'
require 'yaml'
require 'opennebula'
require 'base64'
require 'openssl'

module VCenterDriver

################################################################################
# This class represents a VCenter connection and an associated OpenNebula client
# The connection is associated to the VCenter backing a given OpenNebula host.
# For the VCenter driver each OpenNebula host represents a VCenter cluster
################################################################################
class VIClient
    attr_reader :vim, :one, :root, :cluster, :user, :pass, :host

    def get_entities(folder, type, entities=[])
        return nil if folder == []

        folder.childEntity.each do |child|
            name, junk = child.to_s.split('(')

            case name
            when "Folder"
                get_entities(child, type, entities)
            when type
                entities.push(child)
            end
        end

        return entities
    end

    ############################################################################
    # Initializr the VIClient, and creates an OpenNebula client. The parameters
    # are obtained from the associated OpenNebula host
    # @param hid [Integer] The OpenNebula host id with VCenter attributes
    ############################################################################
    def initialize(hid)

        initialize_one

        @one_host = ::OpenNebula::Host.new_with_id(hid, @one)
        rc = @one_host.info

        if ::OpenNebula.is_error?(rc)
            raise "Error getting host information: #{rc.message}"
        end

        password = @one_host["TEMPLATE/VCENTER_PASSWORD"]

        if !@token.nil?
            begin
                cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")

                cipher.decrypt
                cipher.key = @token

                password =  cipher.update(Base64::decode64(password))
                password << cipher.final
            rescue
                raise "Error decrypting vCenter password"
            end
        end

        connection = {
            :host     => @one_host["TEMPLATE/VCENTER_HOST"],
            :user     => @one_host["TEMPLATE/VCENTER_USER"],
            :password => password
        }

        initialize_vim(connection)

        datacenters = get_entities(@root, 'Datacenter')

        datacenters.each {|dc|
            ccrs = get_entities(dc.hostFolder, 'ClusterComputeResource')

            next if ccrs.nil?

            @cluster = ccrs.find{ |ccr| @one_host.name == ccr.name }

            (@dc = dc; break) if @cluster
        }

        if @dc.nil? || @cluster.nil?
            raise "Cannot find DataCenter or ClusterComputeResource for host."
        end
    end

    ########################################################################
    # Initialize a VIConnection based just on the VIM parameters. The
    # OpenNebula client is also initilialized
    ########################################################################
    def self.new_connection(user_opts)

        conn = allocate

        conn.initialize_one

        conn.initialize_vim(user_opts)

        return conn
    end

    ########################################################################
    # The associated resource pool for this connection
    ########################################################################
    def resource_pool
        return @cluster.resourcePool
    end

    ########################################################################
    # Searches the associated vmFolder of the DataCenter for the current
    # connection. Returns a RbVmomi::VIM::VirtualMachine or nil if not found
    # @param uuid [String] the UUID of the VM or VM Template
    ########################################################################
    def find_vm_template(uuid)
        vms = get_entities(@dc.vmFolder, 'VirtualMachine')

        return vms.find do |v|
            begin
                v.config && v.config.uuid == uuid
            rescue ManagedObjectNotFound
                false
            end
        end
    end

    ########################################################################
    # Searches the associated vmFolder of the DataCenter for the current
    # connection. Returns a RbVmomi::VIM::VirtualMachine or nil if not found
    # @param vm_name [String] the UUID of the VM or VM Template
    ########################################################################
    def find_vm(vm_name)
        vms = get_entities(@dc.vmFolder, 'VirtualMachine')

        return vms.find do |v|
            begin
                v.name == vm_name
            rescue ManagedObjectNotFound
                false
            end
        end
    end

    ########################################################################
    # Builds a hash with the DataCenter / ClusterComputeResource hierarchy
    # for this VCenter.
    # @return [Hash] in the form
    #   {dc_name [String] => ClusterComputeResources Names [Array - String]}
    ########################################################################
    def hierarchy
        vc_hosts = {}

        datacenters = get_entities(@root, 'Datacenter')

        datacenters.each { |dc|
            ccrs = get_entities(dc.hostFolder, 'ClusterComputeResource')
            vc_hosts[dc.name] = ccrs.collect { |c| c.name }
        }

        return vc_hosts
    end

    ########################################################################
    # Builds a hash with the Datacenter / VM Templates for this VCenter
    # @param one_client [OpenNebula::Client] Use this client instead of @one
    # @return [Hash] in the form
    #   { dc_name [String] => }
    ########################################################################
    def vm_templates(one_client=nil)
        vm_templates = {}

        tpool = OpenNebula::TemplatePool.new(
            (one_client||@one), OpenNebula::Pool::INFO_ALL)
        rc = tpool.info
        # TODO check error

        datacenters = get_entities(@root, 'Datacenter')

        datacenters.each { |dc|
            vms = get_entities(dc.vmFolder, 'VirtualMachine')

            tmp = vms.select { |v| v.config.template == true }

            one_tmp = []

            tmp.each { |t|
                vi_tmp = VCenterVm.new(self, t)

                if !tpool["VMTEMPLATE/TEMPLATE/PUBLIC_CLOUD[\
                        TYPE=\"vcenter\" \
                        and VM_TEMPLATE=\"#{vi_tmp.vm.config.uuid}\"]"]
                    one_tmp << {
                        :name => vi_tmp.vm.name,
                        :uuid => vi_tmp.vm.config.uuid,
                        :host => vi_tmp.vm.runtime.host.parent.name,
                        :one  => vi_tmp.to_one
                    }
                end
            }

            vm_templates[dc.name] = one_tmp
        }

        return vm_templates
    end

    ########################################################################
    # Builds a hash with the Datacenter / Virtual Machines for this VCenter
    # @param one_client [OpenNebula::Client] Use this client instead of @one
    # @return [Hash] in the form
    #   { dc_name [String] => }
    ########################################################################
    def running_vms(one_client=nil)
        running_vms = {}

        vmpool = OpenNebula::VirtualMachinePool.new(
            (one_client||@one), OpenNebula::Pool::INFO_ALL)
        rc = vmpool.info

        hostpool = OpenNebula::HostPool.new((one_client||@one))
        rc = hostpool.info
        # TODO check error

        datacenters = get_entities(@root, 'Datacenter')

        datacenters.each { |dc|
            vms     = get_entities(dc.vmFolder, 'VirtualMachine')
            ccrs    = get_entities(dc.hostFolder, 'ClusterComputeResource')

            vm_list = vms.select { |v|
                # Get rid of VM Templates and VMs not in running state
                v.config &&
                v.config.template != true &&
                v.summary.runtime.powerState == "poweredOn"
            }

            one_tmp = []

            vm_list.each { |v|
                vi_tmp = VCenterVm.new(self, v)

                # Do not reimport VMs deployed by OpenNebula
                # since the core will get confused with the IDs
                next if vi_tmp.vm.name.match(/one-\d/)

                container_hostname = vi_tmp.vm.runtime.host.parent.name

                cluster_name = ccrs.collect { |c|
                  found_host=c.host.select {|h|
                           h.parent.name == container_hostname}
                   found_host.first.parent.name if found_host.size > 0
                }.first

                if !vmpool["VM/USER_TEMPLATE/PUBLIC_CLOUD[\
                        TYPE=\"vcenter\" \
                        and VM_TEMPLATE=\"#{vi_tmp.vm.config.uuid}\"]"]

                    host_id = name_to_id(container_hostname,hostpool,"HOST")[1]

                    one_tmp << {
                        :name => vi_tmp.vm.name,
                        :uuid => vi_tmp.vm.config.uuid,
                        :host => container_hostname,
                        :host_id => host_id,
                        :one  => vi_tmp.vm_to_one
                    }
                end
            }

            running_vms[dc.name] = one_tmp
        }

        return running_vms
    end

    def name_to_id(name, pool, ename)
            objects=pool.select {|object| object.name==name }

            if objects.length>0
                if objects.length>1
                    return -1, "There are multiple #{ename}s with name #{name}."
                else
                    result = objects.first.id
                end
            else
                return -1, "#{ename} named #{name} not found."
            end

            return 0, result
    end

    ########################################################################
    # Builds a hash with the Datacenter / CCR (Distributed)Networks
    # for this VCenter
    # @param one_client [OpenNebula::Client] Use this client instead of @one
    # @return [Hash] in the form
    #   { dc_name [String] => Networks [Array] }
    ########################################################################
    def vcenter_networks(one_client=nil)
        vcenter_networks = {}

        vnpool = OpenNebula::VirtualNetworkPool.new(
            (one_client||@one), OpenNebula::Pool::INFO_ALL)
        rc = vnpool.info
        # TODO check error
        #
        datacenters = get_entities(@root, 'Datacenter')

        datacenters.each { |dc|
            networks = get_entities(dc.networkFolder, 'Network' )
            one_nets = []

            networks.each { |n|
                if !vnpool["VNET[BRIDGE=\"#{n[:name]}\"]/\
                        TEMPLATE[VCENTER_TYPE=\"Port Group\"]"]
                    one_nets << {
                        :name   => n.name,
                        :bridge => n.name,
                        :type   => "Port Group",
                        :one    => "NAME   = \"#{n[:name]}\"\n" \
                                   "BRIDGE = \"#{n[:name]}\"\n" \
                                   "VCENTER_TYPE = \"Port Group\""
                    }
                end
            }

            networks = get_entities(dc.networkFolder,
                                    'DistributedVirtualPortgroup' )

            networks.each { |n|
                if !vnpool["VNET[BRIDGE=\"#{n[:name]}\"]/\
                        TEMPLATE[VCENTER_TYPE=\"Distributed Port Group\"]"]
                    vnet_template = "NAME   = \"#{n[:name]}\"\n" \
                                    "BRIDGE = \"#{n[:name]}\"\n" \
                                    "VCENTER_TYPE = \"Distributed Port Group\""

                    default_pc = n.config.defaultPortConfig

                    has_vlan = false
                    vlan_str = ""

                    if default_pc.methods.include? :vlan
                       has_vlan = default_pc.vlan.methods.include? :vlanId
                    end

                    if has_vlan
                        vlan     = n.config.defaultPortConfig.vlan.vlanId

                        if vlan != 0
                            if vlan.is_a? Array
                                vlan.each{|v|
                                    vlan_str += v.start.to_s + ".." +
                                                v.end.to_s + ","
                                }
                                vlan_str.chop!
                            else
                                vlan_str = vlan.to_s
                            end
                        end
                    end

                    if !vlan_str.empty?
                        vnet_template << "VLAN=\"YES\"\n" \
                                         "VLAN_ID=#{vlan_str}\n"
                    end

                    one_net = {:name   => n.name,
                               :bridge => n.name,
                               :type   => "Distributed Port Group",
                               :one    => vnet_template}

                    one_net[:vlan] = vlan_str if !vlan_str.empty?

                    one_nets << one_net
                end
            }

            vcenter_networks[dc.name] = one_nets
        }

        return vcenter_networks
    end

    def self.translate_hostname(hostname)
        host_pool = OpenNebula::HostPool.new(::OpenNebula::Client.new())
        rc        = host_pool.info
        raise "Could not find host #{hostname}" if OpenNebula.is_error?(rc)

        host = host_pool.select {|host_element| host_element.name==hostname }
        return host.first.id
    end

    ############################################################################
    # Initialize an OpenNebula connection with the default ONE_AUTH
    ############################################################################
    def initialize_one
        begin
            @one   = ::OpenNebula::Client.new()
            system = ::OpenNebula::System.new(@one)

            config = system.get_configuration()

            if ::OpenNebula.is_error?(config)
                raise "Error getting oned configuration : #{config.message}"
            end

            @token = config["ONE_KEY"]
        rescue Exception => e
            raise "Error initializing OpenNebula client: #{e.message}"
        end
    end

    ############################################################################
    # Initialize a connection with vCenter. Options
    # @param options[Hash] with:
    #    :user => The vcenter user
    #    :password => Password for the user
    #    :host => vCenter hostname or IP
    #    :insecure => SSL (optional, defaults to true)
    ############################################################################
    def initialize_vim(user_opts={})
        opts = {
            :insecure => true
        }.merge(user_opts)

        @user = opts[:user]
        @pass = opts[:password]
        @host = opts[:host]

        begin
            @vim  = RbVmomi::VIM.connect(opts)
            @root = @vim.root
        rescue Exception => e
            raise "Error connecting to #{@host}: #{e.message}"
        end
    end
end

################################################################################
# This class is an OpenNebula hosts that abstracts a vCenter cluster. It
# includes the functionality needed to monitor the cluster and report the ESX
# hosts and VM status of the cluster.
################################################################################
class VCenterHost < ::OpenNebula::Host
    attr_reader :vc_client, :vc_root, :cluster, :host, :client

    ############################################################################
    # Initialize the VCenterHost by looking for the associated objects of the
    # VIM hierarchy
    # client [VIClient] to interact with the associated vCenter
    ############################################################################
    def initialize(client)
        @client  = client
        @cluster = client.cluster

        @resource_pool = client.resource_pool
    end

    ########################################################################
    #  Creates an OpenNebula host representing a cluster in this VCenter
    #  @param cluster_name[String] the name of the cluster in the vcenter
    #  @param client [VIClient] to create the host
    #  @return In case of success [0, host_id] or [-1, error_msg]
    ########################################################################
    def self.to_one(cluster_name, client)
        one_host = ::OpenNebula::Host.new(::OpenNebula::Host.build_xml,
            client.one)

        rc = one_host.allocate(cluster_name, 'vcenter', 'vcenter', 'dummy',
                ::OpenNebula::ClusterPool::NONE_CLUSTER_ID)

        return -1, rc.message if ::OpenNebula.is_error?(rc)

        template = "VCENTER_HOST=\"#{client.host}\"\n"\
                   "VCENTER_PASSWORD=\"#{client.pass}\"\n"\
                   "VCENTER_USER=\"#{client.user}\"\n"

        rc = one_host.update(template, false)

        if ::OpenNebula.is_error?(rc)
            error = rc.message

            rc = one_host.delete

            if ::OpenNebula.is_error?(rc)
                error << ". Host #{cluster_name} could not be"\
                    " deleted: #{rc.message}."
            end

            return -1, error
        end

        return 0, one_host.id
    end

    ############################################################################
    # Generate an OpenNebula monitor string for this host. Reference:
    # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.ComputeResource.Summary.html
    #   - effectiveCpu: Effective CPU resources (in MHz) available to run
    #     VMs. This is the aggregated from all running hosts excluding hosts in
    #     maintenance mode or unresponsive are not counted.
    #   - effectiveMemory: Effective memory resources (in MB) available to run
    #     VMs. Equivalente to effectiveCpu.
    #   - numCpuCores: Number of physical CPU cores.
    #   - numEffectiveHosts: Total number of effective hosts.
    #   - numHosts:Total number of hosts.
    #   - totalCpu: Aggregated CPU resources of all hosts, in MHz.
    #   - totalMemory: Aggregated memory resources of all hosts, in bytes.
    ############################################################################
    def monitor_cluster
        #Load the host systems
        summary = @cluster.summary

        mhz_core = summary.totalCpu.to_f / summary.numCpuCores.to_f
        eff_core = summary.effectiveCpu.to_f / mhz_core

        free_cpu  = sprintf('%.2f', eff_core * 100).to_f
        total_cpu = summary.numCpuCores.to_f * 100
        used_cpu  = sprintf('%.2f', total_cpu - free_cpu).to_f

        total_mem = summary.totalMemory.to_i / 1024
        free_mem  = summary.effectiveMemory.to_i * 1024

        str_info = ""

        # System
        str_info << "HYPERVISOR=vcenter\n"
        str_info << "PUBLIC_CLOUD=YES\n"
        str_info << "TOTALHOST=" << summary.numHosts.to_s << "\n"
        str_info << "AVAILHOST=" << summary.numEffectiveHosts.to_s << "\n"

        # CPU
        str_info << "CPUSPEED=" << mhz_core.to_s   << "\n"
        str_info << "TOTALCPU=" << total_cpu.to_s << "\n"
        str_info << "USEDCPU="  << used_cpu.to_s  << "\n"
        str_info << "FREECPU="  << free_cpu.to_s << "\n"

        # Memory
        str_info << "TOTALMEMORY=" << total_mem.to_s << "\n"
        str_info << "FREEMEMORY="  << free_mem.to_s << "\n"
        str_info << "USEDMEMORY="  << (total_mem - free_mem).to_s
    end

    ############################################################################
    # Generate a template with information for each ESX Host. Reference:
    # http://pubs.vmware.com/vi-sdk/visdk250/ReferenceGuide/vim.HostSystem.html
    #   - Summary: Basic information about the host, including connection state
    #     - hardware: Hardware configuration of the host. This might not be
    #       available for a disconnected host.
    #     - quickStats: Basic host statistics.
    ############################################################################
    def monitor_host_systems
        host_info = ""

        @cluster.host.each{|h|
            next if h.runtime.connectionState != "connected"

            summary = h.summary
            hw      = summary.hardware
            stats   = summary.quickStats

            total_cpu = hw.numCpuCores * 100
            used_cpu  = (stats.overallCpuUsage.to_f / hw.cpuMhz.to_f) * 100
            used_cpu  = sprintf('%.2f', used_cpu).to_f # Trim precission
            free_cpu  = total_cpu - used_cpu

            total_memory = hw.memorySize/1024
            used_memory  = stats.overallMemoryUsage*1024
            free_memory  = total_memory - used_memory

            host_info << "\nHOST=["
            host_info << "STATE=on,"
            host_info << "HOSTNAME=\""  << h.name.to_s  << "\","
            host_info << "MODELNAME=\"" << hw.cpuModel.to_s  << "\","
            host_info << "CPUSPEED="    << hw.cpuMhz.to_s    << ","
            host_info << "MAX_CPU="    << total_cpu.to_s << ","
            host_info << "USED_CPU="     << used_cpu.to_s  << ","
            host_info << "FREE_CPU="     << free_cpu.to_s << ","
            host_info << "MAX_MEM=" << total_memory.to_s << ","
            host_info << "USED_MEM="  << used_memory.to_s  << ","
            host_info << "FREE_MEM="  << free_memory.to_s
            host_info << "]"
        }

        return host_info
    end

    def monitor_vms
        str_info = ""
        @resource_pool.vm.each { |v|
            name   = v.name
            number = -1
            number = name.split('-').last if (name =~ /^one-\d*$/)

            vm = VCenterVm.new(@client, v)
            vm.monitor

            next if !vm.vm.config

            str_info << "\nVM = ["
            str_info << "ID=#{number},"
            str_info << "DEPLOY_ID=\"#{vm.vm.config.uuid}\","
            str_info << "VM_NAME=\"#{name}\","
            str_info << "POLL=\"#{vm.info}\"]"
        }

        return str_info
    end
end

################################################################################
# This class is a high level abstraction of a VI VirtualMachine class with
# OpenNebula semantics.
################################################################################

class VCenterVm
    attr_reader :vm

    ############################################################################
    #  Creates a new VIVm using a RbVmomi::VirtualMachine object
    #    @param client [VCenterClient] client to connect to vCenter
    #    @param vm_vi [RbVmomi::VirtualMachine] it will be used if not nil
    ########################################################################
    def initialize(client, vm_vi )
        @vm     = vm_vi
        @client = client

        @used_cpu    = 0
        @used_memory = 0

        @net_rx = 0
        @net_tx = 0
    end

    ############################################################################
    # Deploys a VM
    #  @xml_text XML repsentation of the VM
    ############################################################################
    def self.deploy(xml_text, lcm_state, deploy_id, hostname)
        if lcm_state == "BOOT"
            return clone_vm(xml_text)
        else
            hid         = VIClient::translate_hostname(hostname)
            connection  = VIClient.new(hid)
            vm          = connection.find_vm_template(deploy_id)
            vm.PowerOnVM_Task.wait_for_completion
            return vm.config.uuid
        end
    end

    ############################################################################
    # Cancels a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.cancel(deploy_id, hostname, lcm_state)
        case lcm_state
            when "SHUTDOWN_POWEROFF", "SHUTDOWN_UNDEPLOY"
                shutdown(deploy_id, hostname, lcm_state)
            when "CANCEL", "LCM_INIT", "CLEANUP_RESUBMIT"
                hid         = VIClient::translate_hostname(hostname)
                connection  = VIClient.new(hid)
                vm          = connection.find_vm_template(deploy_id)

                begin
                    vm.PowerOffVM_Task.wait_for_completion
                rescue
                end
                vm.Destroy_Task.wait_for_completion
        end
    end

    ############################################################################
    # Saves a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.save(deploy_id, hostname, lcm_state)
        case lcm_state
            when "SAVE_MIGRATE"
                raise "Migration between vCenters cluster not supported"
            when "SAVE_SUSPEND", "SAVE_STOP"
                hid         = VIClient::translate_hostname(hostname)
                connection  = VIClient.new(hid)
                vm          = connection.find_vm_template(deploy_id)

                vm.SuspendVM_Task.wait_for_completion
        end
    end

    ############################################################################
    # Resumes a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.resume(deploy_id, hostname)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)
        vm          = connection.find_vm_template(deploy_id)

        vm.PowerOnVM_Task.wait_for_completion
    end

    ############################################################################
    # Reboots a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.reboot(deploy_id, hostname)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        vm.RebootGuest.wait_for_completion
    end

    ############################################################################
    # Resets a VM
    #  @param deploy_id vcetranslate_hostnamnter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.reset(deploy_id, hostname)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        vm.ResetVM_Task.wait_for_completion
    end

    ############################################################################
    # Shutdown a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    ############################################################################
    def self.shutdown(deploy_id, hostname, lcm_state)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        case lcm_state
            when "SHUTDOWN"
                begin
                    vm.ShutdownGuest.wait_for_completion
                rescue
                end
                vm.PowerOffVM_Task.wait_for_completion
                vm.Destroy_Task.wait_for_completion
            when "SHUTDOWN_POWEROFF", "SHUTDOWN_UNDEPLOY"
                begin
                    vm.ShutdownGuest.wait_for_completion
                rescue
                end
                vm.PowerOffVM_Task.wait_for_completion
        end
    end

    ############################################################################
    # Create VM snapshot
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    #  @param snaphot_name name of the snapshot
    ############################################################################
    def self.create_snapshot(deploy_id, hostname, snapshot_name)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        snapshot_hash = {
            :name => snapshot_name,
            :description => "OpenNebula Snapshot of VM #{deploy_id}",
            :memory => true,
            :quiesce => true
        }

        vm          = connection.find_vm_template(deploy_id)

        vm.CreateSnapshot_Task(snapshot_hash).wait_for_completion

        return snapshot_name
    end

    ############################################################################
    # Find VM snapshot
    #  @param list root list of VM snapshots
    #  @param snaphot_name name of the snapshot
    ############################################################################
    def self.find_snapshot(list, snapshot_name)
        list.each do |i|
            if i.name == snapshot_name
                return i.snapshot
            elsif !i.childSnapshotList.empty?
                snap = find_snapshot(i.childSnapshotList, snapshot_name)
                return snap if snap
            end
        end

        nil
    end

    ############################################################################
    # Delete VM snapshot
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    #  @param snaphot_name name of the snapshot
    ############################################################################
    def self.delete_snapshot(deploy_id, hostname, snapshot_name)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        list = vm.snapshot.rootSnapshotList

        snapshot = find_snapshot(list, snapshot_name)
        return nil if !snapshot

        delete_snapshot_hash = {
            :_this => snapshot,
            :removeChildren => false
        }

        snapshot.RemoveSnapshot_Task(delete_snapshot_hash).wait_for_completion
    end

    ############################################################################
    # Revert VM snapshot
    #  @param deploy_id vcenter identifier of the VM
    #  @param hostname name of the host (equals the vCenter cluster)
    #  @param snaphot_name name of the snapshot
    ############################################################################
    def self.revert_snapshot(deploy_id, hostname, snapshot_name)
        hid         = VIClient::translate_hostname(hostname)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        list = vm.snapshot.rootSnapshotList

        snapshot = find_snapshot(list, snapshot_name)
        return nil if !snapshot

        revert_snapshot_hash = {
            :_this => snapshot
        }

        snapshot.RevertToSnapshot_Task(revert_snapshot_hash).wait_for_completion
    end

    ############################################################################
    # Attach NIC to a VM
    #  @param deploy_id vcenter identifier of the VM
    #  @param mac MAC address of the NIC to be attached
    #  @param bridge name of the Network in vCenter
    #  @param model model of the NIC to be attached
    #  @param host hostname of the ESX where the VM is running
    ############################################################################
    def self.attach_nic(deploy_id, mac, bridge, model, host)
        hid         = VIClient::translate_hostname(host)
        connection  = VIClient.new(hid)

        vm          = connection.find_vm_template(deploy_id)

        spec_hash   = calculate_addnic_spec(vm, mac, bridge, model)

        spec        = RbVmomi::VIM.VirtualMachineConfigSpec({:deviceChange =>
                                                              [spec_hash]})

        vm.ReconfigVM_Task(:spec => spec).wait_for_completion
    end

    ############################################################################
    # Detach NIC from a VM
    ############################################################################
    def self.detach_nic(deploy_id, mac, host)
        hid         = VIClient::translate_hostname(host)
        connection  = VIClient.new(hid)

        vm   = connection.find_vm_template(deploy_id)

        nic  = vm.config.hardware.device.find { |d|
                is_nic?(d) && (d.macAddress ==  mac)
        }

        raise "Could not find NIC with mac address #{mac}" if nic.nil?

        spec = {
            :deviceChange => [
                :operation => :remove,
                :device => nic
            ]
        }

        vm.ReconfigVM_Task(:spec => spec).wait_for_completion
    end

    ########################################################################
    #  Initialize the vm monitor information
    ########################################################################
    def monitor
        @summary = @vm.summary
        @state   = state_to_c(@summary.runtime.powerState)

        if @state != 'a'
            @used_cpu    = 0
            @used_memory = 0

            @net_rx = 0
            @net_tx = 0

            return
        end

        @used_memory = @summary.quickStats.hostMemoryUsage * 1024

        host   = @vm.runtime.host
        cpuMhz = host.summary.hardware.cpuMhz.to_f

        @used_cpu   =
                ((@summary.quickStats.overallCpuUsage.to_f / cpuMhz) * 100).to_s
        @used_cpu   = sprintf('%.2f',@used_cpu).to_s

        # Check for negative values
        @used_memory = 0 if @used_memory.to_i < 0
        @used_cpu    = 0 if @used_cpu.to_i < 0

        @esx_host       = @vm.summary.runtime.host.name
        @guest_ip       = @vm.guest.ipAddress
        @guest_state    = @vm.guest.guestState
        @vmware_tools   = @vm.guest.toolsRunningStatus
        @vmtools_ver    = @vm.guest.toolsVersion
        @vmtools_verst  = @vm.guest.toolsVersionStatus

    end

    ########################################################################
    #  Generates a OpenNebula IM Driver valid string with the monitor info
    ########################################################################
    def info
      return 'STATE=d' if @state == 'd'

      str_info = ""

      str_info << "GUEST_IP=" << @guest_ip.to_s << " " if @guest_ip
      str_info << "STATE="                      << @state                << " "
      str_info << "USEDCPU="                    << @used_cpu.to_s        << " "
      str_info << "USEDMEMORY="                 << @used_memory.to_s     << " "
      str_info << "NETRX="                      << @net_rx.to_s          << " "
      str_info << "NETTX="                      << @net_tx.to_s          << " "
      str_info << "ESX_HOST="                   << @esx_host.to_s        << " "
      str_info << "GUEST_STATE="                << @guest_state.to_s     << " "
      str_info << "VMWARETOOLS_RUNNING_STATUS=" << @vmware_tools.to_s    << " "
      str_info << "VMWARETOOLS_VERSION="        << @vmtools_ver.to_s     << " "
      str_info << "VMWARETOOLS_VERSION_STATUS=" << @vmtools_verst.to_s   << " "
    end

    ########################################################################
    # Generates an OpenNebula Template for this VCenterVm
    #
    #
    ########################################################################
    def to_one
        str = "NAME   = \"#{@vm.name}\"\n"\
              "CPU    = \"#{@vm.config.hardware.numCPU}\"\n"\
              "vCPU   = \"#{@vm.config.hardware.numCPU}\"\n"\
              "MEMORY = \"#{@vm.config.hardware.memoryMB}\"\n"\
              "HYPERVISOR = \"vcenter\"\n"\
              "PUBLIC_CLOUD = [\n"\
              "  TYPE        =\"vcenter\",\n"\
              "  VM_TEMPLATE =\"#{@vm.config.uuid}\"\n"\
              "]\n"\
              "GRAPHICS = [\n"\
              "  TYPE     =\"vnc\",\n"\
              "  LISTEN   =\"0.0.0.0\"\n"\
              "]\n"\
         "SCHED_REQUIREMENTS=\"NAME=\\\"#{@vm.runtime.host.parent.name}\\\"\"\n"

        if @vm.config.annotation.nil? || @vm.config.annotation.empty?
            str << "DESCRIPTION = \"vCenter Template imported by OpenNebula"\
                " from Cluster #{@vm.runtime.host.parent.name}\"\n"
        else
            notes = @vm.config.annotation.gsub("\\", "\\\\").gsub("\"", "\\\"")
            str << "DESCRIPTION = \"#{notes}\"\n"
        end

        case @vm.guest.guestFullName
            when /CentOS/i
                str << "LOGO=images/logos/centos.png"
            when /Debian/i
                str << "LOGO=images/logos/debian.png"
            when /Red Hat/i
                str << "LOGO=images/logos/redhat.png"
            when /Ubuntu/i
                str << "LOGO=images/logos/ubuntu.png"
            when /Windows XP/i
                str << "LOGO=images/logos/windowsxp.png"
            when /Windows/i
                str << "LOGO=images/logos/windows8.png"
            when /Linux/i
                str << "LOGO=images/logos/linux.png"
        end

        return str
    end

    ########################################################################
    # Generates an OpenNebula VirtualMachine for this VCenterVm
    #
    #
    ########################################################################
    def vm_to_one
        str = "NAME   = \"#{@vm.name}\"\n"\
              "CPU    = \"#{@vm.config.hardware.numCPU}\"\n"\
              "vCPU   = \"#{@vm.config.hardware.numCPU}\"\n"\
              "MEMORY = \"#{@vm.config.hardware.memoryMB}\"\n"\
              "HYPERVISOR = \"vcenter\"\n"\
              "PUBLIC_CLOUD = [\n"\
              "  TYPE        =\"vcenter\",\n"\
              "  VM_TEMPLATE =\"#{@vm.config.uuid}\"\n"\
              "]\n"\
              "IMPORT_VM_ID    = \"#{@vm.config.uuid}\"\n"\
              "SCHED_REQUIREMENTS=\"NAME=\\\"#{@vm.runtime.host.parent.name}\\\"\"\n"

        vp=@vm.config.extraConfig.select{|v| v[:key]=="remotedisplay.vnc.port"}

        if vp.size > 0
            str << "GRAPHICS = [\n"\
                   "  TYPE     =\"vnc\",\n"\
                   "  LISTEN   =\"0.0.0.0\",\n"\
                   "  PORT     =\"#{vp[0][:value]}\"\n"\
                   "]\n"
        end

        if @vm.config.annotation.nil? || @vm.config.annotation.empty?
            str << "DESCRIPTION = \"vCenter Virtual Machine imported by OpenNebula"\
                " from Cluster #{@vm.runtime.host.parent.name}\"\n"
        else
            notes = @vm.config.annotation.gsub("\\", "\\\\").gsub("\"", "\\\"")
            str << "DESCRIPTION = \"#{notes}\"\n"
        end

        return str
    end

private

    ########################################################################
    # Converts the VI string state to OpenNebula state convention
    # Guest states are:
    # - poweredOff   The virtual machine is currently powered off.
    # - poweredOn    The virtual machine is currently powered on.
    # - suspended    The virtual machine is currently suspended.
    ########################################################################
    def state_to_c(state)
        case state
            when 'poweredOn'
                'a'
            when 'suspended'
                'p'
            when 'poweredOff'
                'd'
            else
                '-'
        end
    end

    ########################################################################
    #  Checks if a RbVmomi::VIM::VirtualDevice is a network interface
    ########################################################################
    def self.is_nic?(device)
        !device.class.ancestors.index(RbVmomi::VIM::VirtualEthernetCard).nil?
    end

    ########################################################################
    # Returns the spec to reconfig a VM and add a NIC
    ########################################################################
    def self.calculate_addnic_spec(vm, mac, bridge, model)
        model       = model.nil? ? nil : model.downcase
        network     = vm.runtime.host.network.select{|n| n.name==bridge}
        backing     = nil

        if network.empty?
            raise "Network #{bridge} not found in host #{vm.runtime.host.name}"
        else
            network = network[0]
        end

        card_num = 1 # start in one, we want the next avaliable id

        vm.config.hardware.device.each{ |dv|
            card_num = card_num + 1 if is_nic?(dv)
        }

        nic_card = case model
                        when "virtuale1000", "e1000"
                            RbVmomi::VIM::VirtualE1000
                        when "virtuale1000e", "e1000e"
                            RbVmomi::VIM::VirtualE1000e
                        when "virtualpcnet32", "pcnet32"
                            RbVmomi::VIM::VirtualPCNet32
                        when "virtualsriovethernetcard", "sriovethernetcard"
                            RbVmomi::VIM::VirtualSriovEthernetCard
                        when "virtualvmxnetm", "vmxnetm"
                            RbVmomi::VIM::VirtualVmxnetm
                        when "virtualvmxnet2", "vmnet2"
                            RbVmomi::VIM::VirtualVmxnet2
                        when "virtualvmxnet3", "vmxnet3"
                            RbVmomi::VIM::VirtualVmxnet3
                        else # If none matches, use VirtualE1000
                            RbVmomi::VIM::VirtualE1000
                   end

        if network.class == RbVmomi::VIM::Network
            backing = RbVmomi::VIM.VirtualEthernetCardNetworkBackingInfo(
                        :deviceName => bridge,
                        :network => network)
        else
            port    = RbVmomi::VIM::DistributedVirtualSwitchPortConnection(
                        :switchUuid =>
                                network.config.distributedVirtualSwitch.uuid,
                        :portgroupKey => network.key)
            backing =
              RbVmomi::VIM.VirtualEthernetCardDistributedVirtualPortBackingInfo(
                 :port => port)
        end

        return {:operation => :add,
                :device => nic_card.new(
                            :key => 0,
                            :deviceInfo => {
                                :label => "net" + card_num.to_s,
                                :summary => bridge
                            },
                            :backing => backing,
                            :addressType => mac ? 'manual' : 'generated',
                            :macAddress  => mac
                           )
               }
    end

    ########################################################################
    #  Clone a vCenter VM Template and leaves it powered on
    ########################################################################
    def self.clone_vm(xml_text)

        xml = REXML::Document.new xml_text

        pcs = xml.root.get_elements("//USER_TEMPLATE/PUBLIC_CLOUD")

        raise "Cannot find VCenter element in VM template." if pcs.nil?

        template = pcs.find { |t|
            type = t.elements["TYPE"]
            !type.nil? && type.text.downcase == "vcenter"
        }

        raise "Cannot find vCenter element in VM template." if template.nil?

        uuid = template.elements["VM_TEMPLATE"]

        raise "Cannot find VM_TEMPLATE in VCenter element." if uuid.nil?

        uuid = uuid.text

        vmid = xml.root.elements["/VM/ID"].text

        hid = xml.root.elements["//HISTORY_RECORDS/HISTORY/HID"]

        raise "Cannot find host id in deployment file history." if hid.nil?

        context = xml.root.elements["//TEMPLATE/CONTEXT"]

        connection  = VIClient.new(hid)

        vc_template = connection.find_vm_template(uuid)

        relocate_spec = RbVmomi::VIM.VirtualMachineRelocateSpec(
            :diskMoveType => :moveChildMostDiskBacking,
            :pool         => connection.resource_pool)

        clone_spec = RbVmomi::VIM.VirtualMachineCloneSpec(
            :location => relocate_spec,
            :powerOn  => false,
            :template => false)

        begin
            vm = vc_template.CloneVM_Task(
                :folder => vc_template.parent,
                :name   => "one-#{vmid}",
                :spec   => clone_spec).wait_for_completion
        rescue Exception => e

            if !e.message.start_with?('DuplicateName')
                raise "Cannot clone VM Template: #{e.message}"
            end

            vm = connection.find_vm("one-#{vmid}")

            raise "Cannot clone VM Template" if vm.nil?

            vm.Destroy_Task.wait_for_completion

            vm = vc_template.CloneVM_Task(
                :folder => vc_template.parent,
                :name   => "one-#{vmid}",
                :spec   => clone_spec).wait_for_completion
        end

        vm_uuid = vm.config.uuid

        vnc_port   = xml.root.elements["/VM/TEMPLATE/GRAPHICS/PORT"]
        vnc_listen = xml.root.elements["/VM/TEMPLATE/GRAPHICS/LISTEN"]

        if !vnc_listen
            vnc_listen = "0.0.0.0"
        else
            vnc_listen = vnc_listen.text
        end

        config_array     = []
        context_vnc_spec = {}

        if vnc_port
            config_array +=
                     [{:key=>"remotedisplay.vnc.enabled", :value=>"TRUE"},
                      {:key=>"remotedisplay.vnc.port", :value=>vnc_port.text},
                      {:key=>"remotedisplay.vnc.ip",   :value=>vnc_listen}]
        end

        if context
            # Remove <CONTEXT> (9) and </CONTEXT>\n (11)
            context_text = "# Context variables generated by OpenNebula\n"
            context.elements.each{|context_element|
                context_text += context_element.name + "='" +
                                context_element.text.gsub("'", "\\'") + "'\n"
            }
            context_text = Base64.encode64(context_text.chop)
            config_array +=
                     [{:key=>"guestinfo.opennebula.context",
                       :value=>context_text}]
        end

        if config_array != []
            context_vnc_spec = {:extraConfig =>config_array}
        end

        # Take care of the NIC section, build the reconfig hash
        nics     = xml.root.get_elements("//TEMPLATE/NIC")
        nic_spec = {}

        if !nics.nil?
            nic_array = []
            nics.each{|nic|
               mac    = nic.elements["MAC"].text
               bridge = nic.elements["BRIDGE"].text
               model  = nic.elements["MODEL"] ? nic.elements["MODEL"].text : nil
               nic_array << calculate_addnic_spec(vm, mac, bridge, model)
            }

            nic_spec = {:deviceChange => nic_array}
        end

        if !context_vnc_spec.empty? or !nic_spec.empty?
            spec_hash = context_vnc_spec.merge(nic_spec)
            spec      = RbVmomi::VIM.VirtualMachineConfigSpec(spec_hash)
            vm.ReconfigVM_Task(:spec => spec).wait_for_completion
        end

        vm.PowerOnVM_Task.wait_for_completion

        return vm_uuid
    end
end
end


text:
<!doctype html>

	<meta charset="utf-8">
	<title><?php bloginfo( 'name' );
	/*
	 * Print the <title> tag based on what is being viewed.
	 */
	//global $page, $paged, $language;

	//wp_title( '|', true, 'right' );

	// Add the blog description for the home/front page.
	//$site_description = get_bloginfo( 'description', 'display' );
	//if ( $site_description && ( is_home() || is_front_page() ) )
		//echo " | $site_description";

	// Add a page number if necessary:
	//if ( $paged >= 2 || $page >= 2 )
		//echo ' | ' . sprintf( __( 'Page %s', 'lobbybytes' ), max( $paged, $page ) );

//
	?></title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
	<meta name = "format-detection" content = "telephone=no" />

    <link href="<?php bloginfo('stylesheet_url');?>" rel="stylesheet">

    <?php wp_enqueue_script("jquery"); ?>
    <?php wp_head(); ?>

							<?php get_search_form(); ?>

							<a class="homebtn" href="<?php echo site_url(); ?>">Dream Downtown

				<button type="button" class="navbar-toggle sidebar-nav">
							Sidebar
					</button>
          			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

								MENU

					</button>
					<a class="lobo" title="<?php echo get_bloginfo('name'); ?>" href="<?php echo home_url(); ?>"><img class="img-responsive pull-left" title="<?php bloginfo('name');?>" alt="<?php bloginfo('name');?>" src="<?php echo get_bloginfo('template_directory');?>/images/lobo.png ">

						<?php wp_bootstrap_main_nav(); // Adjust using Menus in Wordpress Admin ?>

									<?php echo do_shortcode('[bxs_slider]'); ?>

							<?php the_field('mixcloud-header','option'); ?>
						Pop

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#pragma once

#include "xsapi/title_storage_c.h"

class XSAPI_TITLE_STORAGE_BLOB_METADATA_RESULT_IMPL
{
public:
    void update(const xbox::services::title_storage::title_storage_blob_metadata_result& cppObject);
    const XSAPI_TITLE_STORAGE_BLOB_METADATA* first_item() const;
    size_t item_count() const;
    // TODO We should be able to just return a const ref here, but the cpp get_next API needs to be marked as const first
    /* const */ xbox::services::title_storage::title_storage_blob_metadata_result& cppObject() /* const */;

private:
    std::mutex m_lock;
    std::vector<XSAPI_TITLE_STORAGE_BLOB_METADATA> m_items;
    xbox::services::title_storage::title_storage_blob_metadata_result m_cppObject;
};


text:
cayulo-backend
==============

Estructura del sitio de cuayolo, en este apartado se crea todo lo relacionado con el sitio en el backend.
@Lvcios

### Run Server

```
$ ./manage.py runserver
```


text:
#pragma once

#include "GameState.h"
#include <array>

namespace mnc {

/**
 * Manages a list of pseudo-legal moves in specific game state. The list is divided in multiple
 * priority classes to allow simple and efficient move ordering for the search algorithm.
 * Queen promotions: 3
 * Captures: 0-9 (0 is PxK and 9 is KxP)
 * Killer moves: 10
 * Normal (quiet) moves: 11
 * Promotions to rook/bishop/knight: 12
 */
template<typename T = void>
class MoveList_t
{
public:
	static constexpr unsigned PRIORITIES = 13;

private:
	static constexpr unsigned CAPTURE_PRIORITIES[][6]{
		{0, 8, 8, 9, 9, 9},
		{0, 4, 5, 6, 6, 7},
		{0, 3, 4, 5, 5, 6},
		{0, 2, 3, 4, 4, 5},
		{0, 2, 3, 4, 4, 5},
		{0, 1, 2, 3, 3, 4}
	};

	static constexpr unsigned PROMOTION_PRIORITIES[]{~0U, 3, 12, 12, 12, ~0U};

	static constexpr unsigned KILLER_MOVE_PRIORITY = 10;

	static constexpr unsigned QUIET_MOVE_PRIORITY = 11;

	Move moves[PRIORITIES][256];

	std::array<unsigned, PRIORITIES> moveCounts;

public:

	void populate(const GameState& state, bool excludeQuietMoves,
			const std::array<Move, 2>& killerMoves = std::array<Move, 2>())
	{
		Player player = state.activePlayer();
		clear();

		// Other pieces except pawns.
		for (unsigned piece = 0; piece < Piece::COUNT - 1; ++piece) {
			Mask pieces = state.board()(player, Piece(piece));
			addMoves(state, Piece(piece), pieces, Piece(piece), excludeQuietMoves, killerMoves);
		}

		// Promotable pawns.
		Mask pieces = state.board()(player, Piece::PAWN) & MoveMasks::PROMOTABLE[player];
		if (pieces) {
			for (unsigned promoType = Piece::QUEEN; promoType <= Piece::KNIGHT; ++promoType) {
				addMoves(state, Piece::PAWN, pieces, Piece(promoType), excludeQuietMoves,
						killerMoves);
			}
		}

		// Non-promotable pawns.
		pieces = state.board()(player, Piece::PAWN) & ~MoveMasks::PROMOTABLE[player];
		addMoves(state, Piece::PAWN, pieces, Piece::PAWN, excludeQuietMoves, killerMoves);
	}

	unsigned getCount(int priority) const
	{
		return moveCounts[priority];
	}

	Move getMove(unsigned priority, unsigned idx) const
	{
		return moves[priority][idx];
	}

	void clear()
	{
		moveCounts.fill(0);
	}

private:

	void addMoves(const GameState& state, Piece pieceType, Mask pieces, Piece newType,
			bool excludeQuietMoves, const std::array<Move, 2>& killerMoves)
	{
		Player player = state.activePlayer();
		Mask enPassantMask = getEnPassantMask(state);

		for (Sqr fromSqr : pieces) {
			Mask moves = state.getPseudoLegalMoves(player, pieceType, fromSqr);

			if ((moves & state.board()(~player)) || state.enPassantSqr()) {
				for (unsigned capturedType = 0; capturedType < Piece::COUNT; ++capturedType) {
					Mask captureTargets = state.board()(~player, Piece(capturedType));
					if (pieceType == Piece::PAWN && capturedType == Piece::PAWN)
						captureTargets |= enPassantMask;
					Mask captureMoves = moves & captureTargets;
					for (Sqr toSqr : captureMoves)
						add(pieceType, fromSqr, toSqr, Piece(capturedType), newType, killerMoves);
				}
			}

			if (!excludeQuietMoves) {
				Mask allCaptureTargets = state.board()(~player);
				if (pieceType == Piece::PAWN)
					allCaptureTargets |= enPassantMask;
				Mask quietMoves = moves & ~allCaptureTargets;
				for (Sqr toSqr : quietMoves)
					add(pieceType, fromSqr, toSqr, Piece::NONE, newType, killerMoves);
			}
		}
	}

	Mask getEnPassantMask(const GameState& state) const
	{
		Sqr enPassantSqr = state.enPassantSqr();
		return enPassantSqr ? enPassantSqr : Mask();
	}

	void add(Piece pieceType, Sqr fromSqr, Sqr toSqr, Piece capturedType, Piece newType,
			const std::array<Move, 2>& killerMoves)
	{
		Move move = Move(fromSqr, toSqr, pieceType, capturedType, newType);
		unsigned priority = QUIET_MOVE_PRIORITY;
		if (capturedType)
			priority = CAPTURE_PRIORITIES[pieceType][capturedType];
		else if (newType != pieceType)
			priority = PROMOTION_PRIORITIES[newType];
		else if (move == killerMoves[0] || move == killerMoves[1])
			priority = KILLER_MOVE_PRIORITY;
		unsigned idx = moveCounts[priority]++;
		moves[priority][idx] = move;
	}
};

template<typename T>
constexpr unsigned MoveList_t<T>::CAPTURE_PRIORITIES[][6];

template<typename T>
constexpr unsigned MoveList_t<T>::PROMOTION_PRIORITIES[];

typedef MoveList_t<> MoveList;

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
JsonUtils
</TITLE>

<META NAME="date" CONTENT="2012-03-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.usergrid.android.client.utils

Class JsonUtils

java.lang.Object
  org.usergrid.android.client.utils.JsonUtils

public class JsonUtils
extends java.lang.Object

Constructor Summary

JsonUtils()

Method Summary

static

<T> T

fromJsonNode(org.codehaus.jackson.JsonNode json,
             java.lang.Class<T> c)

static java.lang.Boolean
getBooleanProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                   java.lang.String name)

static java.lang.Long
getLongProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                java.lang.String name)

static

<T> T

getObjectProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                  java.lang.String name,
                  java.lang.Class<T> c)

static java.lang.String
getStringProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                  java.lang.String name)

static java.util.UUID
getUUIDProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                java.lang.String name)

static

<T> T

parse(java.lang.String json,
      java.lang.Class<T> c)

static void
setBooleanProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                   java.lang.String name,
                   java.lang.Boolean value)

static void
setLongProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                java.lang.String name,
                java.lang.Long value)

static void
setObjectProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                  java.lang.String name,
                  java.lang.Object value)

static void
setStringProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                  java.lang.String name,
                  java.lang.String value)

static void
setUUIDProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                java.lang.String name,
                java.util.UUID value)

static org.codehaus.jackson.JsonNode
toJsonNode(java.lang.Object obj)

static java.lang.String
toJsonString(java.lang.Object obj)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

JsonUtils

public JsonUtils()

Method Detail

getStringProperty

public static java.lang.String getStringProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                                 java.lang.String name)

setStringProperty

public static void setStringProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                     java.lang.String name,
                                     java.lang.String value)

getLongProperty

public static java.lang.Long getLongProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                             java.lang.String name)

setLongProperty

public static void setLongProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                   java.lang.String name,
                                   java.lang.Long value)

getBooleanProperty

public static java.lang.Boolean getBooleanProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                                   java.lang.String name)

setBooleanProperty

public static void setBooleanProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                      java.lang.String name,
                                      java.lang.Boolean value)

getUUIDProperty

public static java.util.UUID getUUIDProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                             java.lang.String name)

setUUIDProperty

public static void setUUIDProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                   java.lang.String name,
                                   java.util.UUID value)

toJsonString

public static java.lang.String toJsonString(java.lang.Object obj)

parse

public static <T> T parse(java.lang.String json,
                          java.lang.Class<T> c)

toJsonNode

public static org.codehaus.jackson.JsonNode toJsonNode(java.lang.Object obj)

fromJsonNode

public static <T> T fromJsonNode(org.codehaus.jackson.JsonNode json,
                                 java.lang.Class<T> c)

getObjectProperty

public static <T> T getObjectProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                      java.lang.String name,
                                      java.lang.Class<T> c)

setObjectProperty

public static void setObjectProperty(java.util.Map<java.lang.String,org.codehaus.jackson.JsonNode> properties,
                                     java.lang.String name,
                                     java.lang.Object value)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import VTextField from './VTextField'

export { VTextField }
export default VTextField


text:
"""Unit tests for oauth2_client and related classes."""

from __future__ import absolute_import

import datetime
import logging
import os
import stat
import sys
import unittest

from freezegun import freeze_time
from gcs_oauth2_boto_plugin import oauth2_client
import httplib2

try:
  from unittest import mock
except ImportError:
  import mock

LOG = logging.getLogger('test_oauth2_client')

ACCESS_TOKEN = 'abc123'
RAPT_TOKEN = 'rapt123'
TOKEN_URI = 'https://provider.example.com/oauth/provider?mode=token'
AUTH_URI = 'https://provider.example.com/oauth/provider?mode=authorize'
DEFAULT_CA_CERTS_FILE = os.path.abspath(
    os.path.join('gslib', 'data', 'cacerts.txt'))

IS_WINDOWS = 'win32' in str(sys.platform).lower()

class MockDateTime(object):

  def __init__(self):
    self.mock_now = None

  def utcnow(self):  # pylint: disable=invalid-name
    return self.mock_now

class MockOAuth2ServiceAccountClient(oauth2_client.OAuth2ServiceAccountClient):
  """Mock service account client for testing OAuth2 with service accounts."""

  def __init__(self, client_id, private_key, password, auth_uri, token_uri,
               datetime_strategy):
    super(MockOAuth2ServiceAccountClient, self).__init__(
        client_id, private_key, password, auth_uri=auth_uri,
        token_uri=token_uri, datetime_strategy=datetime_strategy,
        ca_certs_file=DEFAULT_CA_CERTS_FILE)
    self.Reset()

  def Reset(self):
    self.fetched_token = False

  def FetchAccessToken(self, rapt_token=None):
    self.fetched_token = True
    return oauth2_client.AccessToken(
        ACCESS_TOKEN,
        GetExpiry(self.datetime_strategy, 3600),
        datetime_strategy=self.datetime_strategy,
        rapt_token=None)

class MockOAuth2UserAccountClient(oauth2_client.OAuth2UserAccountClient):
  """Mock user account client for testing OAuth2 with user accounts."""

  def __init__(self, token_uri, client_id, client_secret, refresh_token,
               auth_uri, datetime_strategy):
    super(MockOAuth2UserAccountClient, self).__init__(
        token_uri, client_id, client_secret, refresh_token, auth_uri=auth_uri,
        datetime_strategy=datetime_strategy,
        ca_certs_file=DEFAULT_CA_CERTS_FILE)
    self.Reset()

  def Reset(self):
    self.fetched_token = False

  def FetchAccessToken(self, rapt_token=None):
    self.fetched_token = True
    return oauth2_client.AccessToken(
        ACCESS_TOKEN,
        GetExpiry(self.datetime_strategy, 3600),
        datetime_strategy=self.datetime_strategy,
        rapt_token=RAPT_TOKEN if rapt_token is None else rapt_token)

def GetExpiry(datetime_strategy, length_in_seconds):
  token_expiry = (datetime_strategy.utcnow()
                  + datetime.timedelta(seconds=length_in_seconds))
  return token_expiry

def CreateMockUserAccountClient(mock_datetime):
  return MockOAuth2UserAccountClient(
      TOKEN_URI, 'clid', 'clsecret', 'ref_token_abc123', AUTH_URI,
      mock_datetime)

def CreateMockServiceAccountClient(mock_datetime):
  return MockOAuth2ServiceAccountClient(
      'clid', 'private_key', 'password', AUTH_URI, TOKEN_URI, mock_datetime)

class OAuth2AccountClientTest(unittest.TestCase):
  """Unit tests for OAuth2UserAccountClient and OAuth2ServiceAccountClient."""

  def setUp(self):
    self.tempdirs = []
    self.mock_datetime = MockDateTime()
    self.start_time = datetime.datetime(2011, 3, 1, 11, 25, 13, 300826)
    self.mock_datetime.mock_now = self.start_time

  def testGetAccessTokenUserAccount(self):
    self.client = CreateMockUserAccountClient(self.mock_datetime)
    self._RunGetAccessTokenTest(expected_rapt=RAPT_TOKEN)

  def testGetAccessTokenServiceAccount(self):
    self.client = CreateMockServiceAccountClient(self.mock_datetime)
    self._RunGetAccessTokenTest()

  def _RunGetAccessTokenTest(self, expected_rapt=None):
    """Tests access token gets with self.client."""
    access_token_1 = 'abc123'

    self.assertFalse(self.client.fetched_token)
    token_1 = self.client.GetAccessToken()

    # There's no access token in the cache; verify that we fetched a fresh
    # token.
    self.assertTrue(self.client.fetched_token)
    self.assertEqual(access_token_1, token_1.token)
    self.assertEqual(self.start_time + datetime.timedelta(minutes=60),
                     token_1.expiry)
    self.assertEqual(token_1.rapt_token, expected_rapt)

    # Advance time by less than expiry time, and fetch another token.
    self.client.Reset()
    self.mock_datetime.mock_now = (
        self.start_time + datetime.timedelta(minutes=55))
    token_2 = self.client.GetAccessToken()

    # Since the access token wasn't expired, we get the cache token, and there
    # was no refresh request.
    self.assertEqual(token_1, token_2)
    self.assertEqual(access_token_1, token_2.token)
    self.assertFalse(self.client.fetched_token)

    # Advance time past expiry time, and fetch another token.
    self.client.Reset()
    self.mock_datetime.mock_now = (
        self.start_time + datetime.timedelta(minutes=55, seconds=1))
    self.client.datetime_strategy = self.mock_datetime
    token_3 = self.client.GetAccessToken()

    # This should have resulted in a refresh request and a fresh access token.
    self.assertTrue(self.client.fetched_token)
    self.assertEqual(
        self.mock_datetime.mock_now + datetime.timedelta(minutes=60),
        token_3.expiry)
    self.assertEqual(token_3.rapt_token, expected_rapt)

class AccessTokenTest(unittest.TestCase):
  """Unit tests for access token functions."""

  def testShouldRefresh(self):
    """Tests that token.ShouldRefresh returns the correct value."""
    mock_datetime = MockDateTime()
    start = datetime.datetime(2011, 3, 1, 11, 25, 13, 300826)
    expiry = start + datetime.timedelta(minutes=60)
    token = oauth2_client.AccessToken(
        'foo', expiry, datetime_strategy=mock_datetime)

    mock_datetime.mock_now = start
    self.assertFalse(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(minutes=54)
    self.assertFalse(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(minutes=55)
    self.assertFalse(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(
        minutes=55, seconds=1)
    self.assertTrue(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(
        minutes=61)
    self.assertTrue(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(minutes=58)
    self.assertFalse(token.ShouldRefresh(time_delta=120))

    mock_datetime.mock_now = start + datetime.timedelta(
        minutes=58, seconds=1)
    self.assertTrue(token.ShouldRefresh(time_delta=120))

  def testShouldRefreshNoExpiry(self):
    """Tests token.ShouldRefresh with no expiry time."""
    mock_datetime = MockDateTime()
    start = datetime.datetime(2011, 3, 1, 11, 25, 13, 300826)
    token = oauth2_client.AccessToken(
        'foo', None, datetime_strategy=mock_datetime)

    mock_datetime.mock_now = start
    self.assertFalse(token.ShouldRefresh())

    mock_datetime.mock_now = start + datetime.timedelta(
        minutes=472)
    self.assertFalse(token.ShouldRefresh())

  def testSerialization(self):
    """Tests token serialization."""
    expiry = datetime.datetime(2011, 3, 1, 11, 25, 13, 300826)
    token = oauth2_client.AccessToken('foo', expiry, rapt_token=RAPT_TOKEN)
    serialized_token = token.Serialize()
    LOG.debug('testSerialization: serialized_token=%s', serialized_token)

    token2 = oauth2_client.AccessToken.UnSerialize(serialized_token)
    self.assertEqual(token, token2)

class FileSystemTokenCacheTest(unittest.TestCase):
  """Unit tests for FileSystemTokenCache."""

  def setUp(self):
    self.cache = oauth2_client.FileSystemTokenCache()
    self.start_time = datetime.datetime(2011, 3, 1, 10, 25, 13, 300826)
    self.token_1 = oauth2_client.AccessToken(
        'token1', self.start_time, rapt_token=RAPT_TOKEN)
    self.token_2 = oauth2_client.AccessToken(
        'token2', self.start_time + datetime.timedelta(seconds=492),
        rapt_token=RAPT_TOKEN)
    self.key = 'token1key'

  def tearDown(self):
    try:
      os.unlink(self.cache.CacheFileName(self.key))
    except:  # pylint: disable=bare-except
      pass

  def testPut(self):
    self.cache.PutToken(self.key, self.token_1)
    # Assert that the cache file exists and has correct permissions.
    if not IS_WINDOWS:
      self.assertEqual(
          0o600,
          stat.S_IMODE(os.stat(self.cache.CacheFileName(self.key)).st_mode))

  def testPutGet(self):
    """Tests putting and getting various tokens."""
    # No cache file present.
    self.assertEqual(None, self.cache.GetToken(self.key))

    # Put a token
    self.cache.PutToken(self.key, self.token_1)
    cached_token = self.cache.GetToken(self.key)
    self.assertEqual(self.token_1, cached_token)

    # Put a different token
    self.cache.PutToken(self.key, self.token_2)
    cached_token = self.cache.GetToken(self.key)
    self.assertEqual(self.token_2, cached_token)

  def testGetBadFile(self):
    f = open(self.cache.CacheFileName(self.key), 'w')
    f.write('blah')
    f.close()
    self.assertEqual(None, self.cache.GetToken(self.key))

  def testCacheFileName(self):
    """Tests configuring the cache with a specific file name."""
    cache = oauth2_client.FileSystemTokenCache(
        path_pattern='/var/run/ccache/token.%(uid)s.%(key)s')
    if IS_WINDOWS:
      uid = '_'
    else:
      uid = os.getuid()
    self.assertEqual('/var/run/ccache/token.%s.abc123' % uid,
                     cache.CacheFileName('abc123'))

    cache = oauth2_client.FileSystemTokenCache(
        path_pattern='/var/run/ccache/token.%(key)s')
    self.assertEqual('/var/run/ccache/token.abc123',
                     cache.CacheFileName('abc123'))

class RefreshTokenTest(unittest.TestCase):
  """Unit tests for refresh tokens."""

  def setUp(self):
    self.mock_datetime = MockDateTime()
    self.start_time = datetime.datetime(2011, 3, 1, 10, 25, 13, 300826)
    self.mock_datetime.mock_now = self.start_time
    self.client = CreateMockUserAccountClient(self.mock_datetime)

  def testUniqeId(self):
    cred_id = self.client.CacheKey()
    self.assertEqual('0720afed6871f12761fbea3271f451e6ba184bf5', cred_id)

  def testGetAuthorizationHeader(self):
    self.assertEqual('Bearer %s' % ACCESS_TOKEN,
                     self.client.GetAuthorizationHeader())

class FakeResponse(object):

  def __init__(self, status):
    self._status = status

  @property
  def status(self):
    return self._status

class OAuth2GCEClientTest(unittest.TestCase):
  """Unit tests for OAuth2GCEClient."""

  def setUp(self):
    patcher = mock.patch(
        'gcs_oauth2_boto_plugin.oauth2_client.httplib2.Http', autospec=True)
    self.addCleanup(patcher.stop)
    self.mocked_http_class = patcher.start()
    self.mock_http = self.mocked_http_class.return_value

  @freeze_time('2014-03-26 01:01:01')
  def testFetchAccessToken(self):
    token = 'my_token'
    self.mock_http.request.return_value = (
        FakeResponse(200),
        '{"access_token":"%(TOKEN)s", "expires_in": %(EXPIRES_IN)d}' % {
            'TOKEN': token,
            'EXPIRES_IN': 42
        })

    client = oauth2_client.OAuth2GCEClient()

    self.assertEqual(
        str(client.FetchAccessToken()),
        'AccessToken(token=%s, expiry=2014-03-26 01:01:43Z)' % token)
    self.mock_http.request.assert_called_with(
        oauth2_client.META_TOKEN_URI,
        method='GET',
        body=None,
        headers=oauth2_client.META_HEADERS)

  def testIsGCENotFound(self):
    self.mock_http.request.return_value = (FakeResponse(404), '')

    self.assertFalse(oauth2_client._IsGCE())
    self.mock_http.request.assert_called_once_with(
        oauth2_client.METADATA_SERVER)

  def testIsGCEServerNotFound(self):
    self.mock_http.request.side_effect = httplib2.ServerNotFoundError()

    self.assertFalse(oauth2_client._IsGCE())
    self.mock_http.request.assert_called_once_with(
        oauth2_client.METADATA_SERVER)

  def testIsGCETrue(self):
    self.mock_http.request.return_value = (FakeResponse(200), '')

    self.assertTrue(oauth2_client._IsGCE())
    self.mock_http.request.assert_called_once_with(
        oauth2_client.METADATA_SERVER)

if __name__ == '__main__':
  unittest.main()


text:
namespace Construktion.Blueprints
{
    using System;
    using System.Reflection;

    public class DefensiveBlueprint : Blueprint
    {
        public bool Matches(ConstruktionContext context) => true;

        public object Construct(ConstruktionContext context, ConstruktionPipeline pipeline)
        {
            if (context.RequestType.GetTypeInfo().IsInterface)
                throw new Exception($"Cannot construct the interface {context.RequestType.Name}. " +
                                    "You must register it or add a custom blueprint.");

            throw new Exception($"No Blueprint could be found for {context.RequestType.FullName}. Please add " +
                                $"a custom blueprint that can create it.");
        }
    }
}


text:
package com.microsoft.azure.management.deploymentmanager.v2019_11_01_preview;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Defines the artifacts of a service unit.
 */
public class ServiceUnitArtifacts {
    /**
     * The full URI of the ARM template file with the SAS token.
     */
    @JsonProperty(value = "templateUri")
    private String templateUri;

    /**
     * The full URI of the ARM parameters file with the SAS token.
     */
    @JsonProperty(value = "parametersUri")
    private String parametersUri;

    /**
     * The path to the ARM template file relative to the artifact source.
     */
    @JsonProperty(value = "templateArtifactSourceRelativePath")
    private String templateArtifactSourceRelativePath;

    /**
     * The path to the ARM parameters file relative to the artifact source.
     */
    @JsonProperty(value = "parametersArtifactSourceRelativePath")
    private String parametersArtifactSourceRelativePath;

    /**
     * Get the full URI of the ARM template file with the SAS token.
     *
     * @return the templateUri value
     */
    public String templateUri() {
        return this.templateUri;
    }

    /**
     * Set the full URI of the ARM template file with the SAS token.
     *
     * @param templateUri the templateUri value to set
     * @return the ServiceUnitArtifacts object itself.
     */
    public ServiceUnitArtifacts withTemplateUri(String templateUri) {
        this.templateUri = templateUri;
        return this;
    }

    /**
     * Get the full URI of the ARM parameters file with the SAS token.
     *
     * @return the parametersUri value
     */
    public String parametersUri() {
        return this.parametersUri;
    }

    /**
     * Set the full URI of the ARM parameters file with the SAS token.
     *
     * @param parametersUri the parametersUri value to set
     * @return the ServiceUnitArtifacts object itself.
     */
    public ServiceUnitArtifacts withParametersUri(String parametersUri) {
        this.parametersUri = parametersUri;
        return this;
    }

    /**
     * Get the path to the ARM template file relative to the artifact source.
     *
     * @return the templateArtifactSourceRelativePath value
     */
    public String templateArtifactSourceRelativePath() {
        return this.templateArtifactSourceRelativePath;
    }

    /**
     * Set the path to the ARM template file relative to the artifact source.
     *
     * @param templateArtifactSourceRelativePath the templateArtifactSourceRelativePath value to set
     * @return the ServiceUnitArtifacts object itself.
     */
    public ServiceUnitArtifacts withTemplateArtifactSourceRelativePath(String templateArtifactSourceRelativePath) {
        this.templateArtifactSourceRelativePath = templateArtifactSourceRelativePath;
        return this;
    }

    /**
     * Get the path to the ARM parameters file relative to the artifact source.
     *
     * @return the parametersArtifactSourceRelativePath value
     */
    public String parametersArtifactSourceRelativePath() {
        return this.parametersArtifactSourceRelativePath;
    }

    /**
     * Set the path to the ARM parameters file relative to the artifact source.
     *
     * @param parametersArtifactSourceRelativePath the parametersArtifactSourceRelativePath value to set
     * @return the ServiceUnitArtifacts object itself.
     */
    public ServiceUnitArtifacts withParametersArtifactSourceRelativePath(String parametersArtifactSourceRelativePath) {
        this.parametersArtifactSourceRelativePath = parametersArtifactSourceRelativePath;
        return this;
    }

}


text:
/**
 * @author alemures / https://github.com/alemures
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { arrayMin, arrayMax } from '../../../src/utils';

QUnit.module( 'utils', () => {

	QUnit.test( 'arrayMin', ( assert ) => {

		assert.equal( arrayMin( [] ), Infinity, 'Empty array return positive infinit' );
		assert.equal( arrayMin( [ 5 ] ), 5, 'Single valued array should return the unique value as minimum' );
		assert.equal( arrayMin( [ 1, 5, 10 ] ), 1, 'The array [ 1, 5, 10 ] return 1' );
		assert.equal( arrayMin( [ 5, 1, 10 ] ), 1, 'The array [ 5, 1, 10 ] return 1' );
		assert.equal( arrayMin( [ 10, 5, 1 ] ), 1, 'The array [ 10, 5, 1 ] return 1' );
		assert.equal( arrayMax( [ - 0, 0 ] ), - 0, 'The array [ - 0, 0 ] return -0' );
		assert.equal( arrayMin( [ - Infinity, 0, Infinity ] ), - Infinity, 'The array [ - Infinity, 0, Infinity ] return -Infinity' );

	} );

	QUnit.test( 'arrayMax', ( assert ) => {

		assert.equal( arrayMax( [] ), - Infinity, 'Empty array return negative infinit' );
		assert.equal( arrayMax( [ 5 ] ), 5, 'Single valued array should return the unique value as maximum' );
		assert.equal( arrayMax( [ 10, 5, 1 ] ), 10, 'The array [ 10, 5, 1 ] return 10' );
		assert.equal( arrayMax( [ 1, 10, 5 ] ), 10, 'The array [ 1, 10, 5 ] return 10' );
		assert.equal( arrayMax( [ 1, 5, 10 ] ), 10, 'The array [ 1, 5, 10 ] return 10' );
		assert.equal( arrayMax( [ - 0, 0 ] ), 0, 'The array [ - 0, 0 ] return 0' );
		assert.equal( arrayMax( [ - Infinity, 0, Infinity ] ), Infinity, 'The array [ - Infinity, 0, Infinity ] return Infinity' );

	} );

} );


text:
package org.locationtech.geomesa.convert.text

import java.nio.charset.StandardCharsets

import com.google.common.io.Resources
import com.typesafe.config.ConfigFactory
import org.junit.runner.RunWith
import org.locationtech.geomesa.convert.SimpleFeatureConverters
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

@RunWith(classOf[JUnitRunner])
class DelimitedTextConverterTest extends Specification {

  sequential

  "DelimitedTextConverter" should {

    val data =
      """
        |1,hello,45.0,45.0
        |2,world,90.0,90.0
        |willfail,hello
      """.stripMargin

    val conf = ConfigFactory.parseString(
      """
        | converter = {
        |   type         = "delimited-text",
        |   format       = "DEFAULT",
        |   id-field     = "md5(string2bytes($0))",
        |   fields = [
        |     { name = "oneup",    transform = "$1" },
        |     { name = "phrase",   transform = "concat($1, $2)" },
        |     { name = "lat",      transform = "$3::double" },
        |     { name = "lon",      transform = "$4::double" },
        |     { name = "lit",      transform = "'hello'" },
        |     { name = "geom",     transform = "point($lat, $lon)" }
        |     { name = "l1",       transform = "concat($lit, $lit)" }
        |     { name = "l2",       transform = "concat($l1,  $lit)" }
        |     { name = "l3",       transform = "concat($l2,  $lit)" }
        |   ]
        | }
      """.stripMargin)

    val sft = SimpleFeatureTypes.createType(ConfigFactory.load("sft_testsft.conf"))
    "be built from a conf" >> {
      val converter = SimpleFeatureConverters.build[String](sft, conf)
      converter must not beNull

      val res = converter.processInput(data.split("\n").toIterator.filterNot( s => "^\\s*$".r.findFirstIn(s).size > 0)).toList
      converter.close()

      "and process some data" >> {
        res.size must be equalTo 2
        res(0).getAttribute("phrase").asInstanceOf[String] must be equalTo "1hello"
        res(1).getAttribute("phrase").asInstanceOf[String] must be equalTo "2world"
      }

      "handle more derived fields than input fields" >> {
        res(0).getAttribute("oneup").asInstanceOf[String] must be equalTo "1"
      }
    }

    "handle tab delimited files" >> {
      val conf = ConfigFactory.parseString(
        """
          | converter = {
          |   type         = "delimited-text",
          |   format       = "TDF",
          |   id-field     = "md5(string2bytes($0))",
          |   fields = [
          |     { name = "phrase", transform = "concat($1, $2)" },
          |     { name = "lat",    transform = "$3::double" },
          |     { name = "lon",    transform = "$4::double" },
          |     { name = "geom",   transform = "point($lat, $lon)" }
          |   ]
          | }
        """.stripMargin)
      val sft = SimpleFeatureTypes.createType(ConfigFactory.load("sft_testsft.conf"))
      val converter = SimpleFeatureConverters.build[String](sft, conf)
      converter must not beNull
      val res = converter.processInput(data.split("\n").toIterator.filterNot( s => "^\\s*$".r.findFirstIn(s).size > 0).map(_.replaceAll(",", "\t"))).toList
      converter.close()
      res.size must be equalTo 2
      res(0).getAttribute("phrase").asInstanceOf[String] must be equalTo "1hello"
      res(1).getAttribute("phrase").asInstanceOf[String] must be equalTo "2world"
    }

    "handle line number transform and filename global parameter correctly " >> {
      val conf = ConfigFactory.parseString(
        """
          | converter = {
          |   type         = "delimited-text",
          |   format       = "TDF",
          |   id-field     = "md5(string2bytes($0))",
          |   fields = [
          |     { name = "phrase", transform = "concat($1, $2)" },
          |     { name = "lineNr", transform = "lineNo()"},
          |     { name = "fn",     transform = "$filename"},
          |     { name = "lat",    transform = "$3::double" },
          |     { name = "lon",    transform = "$4::double" },
          |     { name = "geom",   transform = "point($lat, $lon)" }
          |   ]
          | }
        """.stripMargin)
      val sft = SimpleFeatureTypes.createType(ConfigFactory.load("sft_testsft.conf"))
      val converter = SimpleFeatureConverters.build[String](sft, conf)
      converter must not beNull
      val input = data.split("\n").toIterator.filterNot( s => "^\\s*$".r.findFirstIn(s).size > 0).map(_.replaceAll(",", "\t"))
      val res = converter.processInput(input, Map("filename"-> "/some/file/path/testfile.txt")).toList
      converter.close()
      res.size must be equalTo 2
      res(0).getAttribute("phrase").asInstanceOf[String] must be equalTo "1hello"
      res(0).getAttribute("lineNr").asInstanceOf[Int] must be equalTo 1
      res(0).getAttribute("fn").asInstanceOf[String] must be equalTo "/some/file/path/testfile.txt"
      res(1).getAttribute("phrase").asInstanceOf[String] must be equalTo "2world"
      res(1).getAttribute("lineNr").asInstanceOf[Int] must be equalTo 2
      res(1).getAttribute("fn").asInstanceOf[String] must be equalTo "/some/file/path/testfile.txt"
    }

    "handle line number transform and filename global in id-field " >> {
      val conf = ConfigFactory.parseString(
        """
          | converter = {
          |   type         = "delimited-text",
          |   format       = "TDF",
          |   id-field     = "concat($filename, lineNo())",
          |   fields = [
          |     { name = "phrase", transform = "concat($1, $2)" },
          |     { name = "lineNr", transform = "lineNo()"},
          |     { name = "fn",     transform = "$filename"},
          |     { name = "lat",    transform = "$3::double" },
          |     { name = "lon",    transform = "$4::double" },
          |     { name = "geom",   transform = "point($lat, $lon)" }
          |   ]
          | }
        """.stripMargin)

      val sft = SimpleFeatureTypes.createType(ConfigFactory.load("sft_testsft.conf"))
      val converter = SimpleFeatureConverters.build[String](sft, conf)
      converter must not beNull
      val input = data.split("\n").toIterator.filterNot( s => "^\\s*$".r.findFirstIn(s).size > 0).map(_.replaceAll(",", "\t"))
      val res = converter.processInput(input, Map("filename"-> "/some/file/path/testfile.txt")).toList
      converter.close()
      res.size must be equalTo 2
      res(0).getAttribute("phrase").asInstanceOf[String] must be equalTo "1hello"
      res(0).getAttribute("lineNr").asInstanceOf[Int] must be equalTo 1
      res(0).getAttribute("fn").asInstanceOf[String] must be equalTo "/some/file/path/testfile.txt"
      res(1).getAttribute("phrase").asInstanceOf[String] must be equalTo "2world"
      res(1).getAttribute("lineNr").asInstanceOf[Int] must be equalTo 2
      res(1).getAttribute("fn").asInstanceOf[String] must be equalTo "/some/file/path/testfile.txt"
    }

    "handle projecting to just the attributes in the SFT (and associated input dependencies)" >> {
      // l3 has cascading dependencies
      val subsft = SimpleFeatureTypes.createType("subsettest", "l3:String,geom:Point:srid=4326")
      val conv = SimpleFeatureConverters.build[String](subsft, conf)
      val res = conv.processInput(data.split("\n").toIterator.filterNot( s => "^\\s*$".r.findFirstIn(s).size > 0)).toList
      conv.close()

      res.length must be equalTo 2
    }

    "handle horrible quoting and nested separators" >> {
      val conf = ConfigFactory.parseString(
        """
          | converter = {
          |   type         = "delimited-text",
          |   format       = "EXCEL",
          |   id-field     = "md5(string2bytes($0))",
          |   fields = [
          |     { name = "phrase", transform = "concat($1, $2)" },
          |     { name = "lat",    transform = "$3::double" },
          |     { name = "lon",    transform = "$4::double" },
          |     { name = "geom",   transform = "point($lat, $lon)" }
          |   ]
          | }
        """.stripMargin)

      import scala.collection.JavaConversions._
      val data = Resources.readLines(Resources.getResource("messydata.csv"), StandardCharsets.UTF_8)

      val sft = SimpleFeatureTypes.createType(ConfigFactory.load("sft_testsft.conf"))
      val converter = SimpleFeatureConverters.build[String](sft, conf)
      converter must not beNull
      val res = converter.processInput(data.iterator()).toList
      converter.close()
      res.size must be equalTo 2
      res(0).getAttribute("phrase").asInstanceOf[String] must be equalTo "1hello, \"foo\""
      res(1).getAttribute("phrase").asInstanceOf[String] must be equalTo "2world"
    }

    "handle records bigger than buffer size" >> {
      // set the buffer size to 16 bytes and try to write records that are bigger than the buffer size

      val sizeConf = ConfigFactory.parseString(
        """
          | converter = {
          |   type         = "delimited-text",
          |   format       = "DEFAULT",
          |   id-field     = "md5(string2bytes($0))",
          |   pipe-size    = 16 // 16 bytes
          |   fields = [
          |     { name = "oneup",  transform = "$1" },
          |     { name = "phrase", transform = "concat($1, $2)" },
          |     { name = "lat",    transform = "$3::double" },
          |     { name = "lon",    transform = "$4::double" },
          |     { name = "lit",    transform = "'hello'" },
          |     { name = "geom",   transform = "point($lat, $lon)" }
          |   ]
          | }
        """.stripMargin)

      val converter = SimpleFeatureConverters.build[String](sft, sizeConf)
      val data =
        """
          |1,hello,45.0,45.0
          |2,world,90.0,90.0
          |willfail,hello
        """.stripMargin

      val nonEmptyData = data.split("\n").toIterator.filterNot(s => "^\\s*$".r.findFirstIn(s).size > 0)
      val res = converter.processInput(nonEmptyData).toList
      converter.close()

      res.size must be greaterThan 0
    }
  }
}


text:
package cn.itcast.domain;

public class Person {
	private Integer id;
	private String name;
	private Integer amount;

	public Integer getAmount() {
		return amount;
	}

	public void setAmount(Integer amount) {
		this.amount = amount;
	}

	public Person(){}

	public Person(Integer id, String name) {
		this.id = id;
		this.name = name;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Person [amount=" + amount + ", id=" + id + ", name=" + name
				+ "]";
	}

}


text:
function Update-PSDriveInfoType {
    <#
        Update PSDriveInfo type to include BlockSize
        Author: Øyvind Kallstad
    #>
    $typeData = Get-TypeData System.Management.Automation.PSDriveInfo
    $scriptBlock = {
        if ($this.Provider.ImplementingType -eq [Microsoft.PowerShell.Commands.FileSystemProvider]) {
            $driveRoot = ([System.IO.DirectoryInfo] $this.Root).Name.Replace('\','\\')
            (Get-WmiObject -Query "SELECT BlockSize FROM Win32_Volume WHERE Name='$driveRoot'").BlockSize
        }
    }
    $scriptProperty = New-Object System.Management.Automation.Runspaces.ScriptPropertyData 'BlockSize', $scriptBlock
    if (-not($typeData.Members['BlockSize'])) {
        $typeData.Members.Add('BlockSize', $scriptProperty)
    }
    Update-TypeData $typeData -Force
}