{"text":"\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ron Dreslinski\n * Steve Reinhardt\n * Ali Saidi\n *\/\n\n\/**\n * @file\n * Declaration of a request, the overall memory request consisting of\n the parts of the request that are persistent throughout the transaction.\n *\/\n\n#ifndef __MEM_REQUEST_HH__\n#define __MEM_REQUEST_HH__\n\n#include \n\n#include \"base\/fast_alloc.hh\"\n#include \"base\/flags.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/types.hh\"\n#include \"sim\/core.hh\"\n\nclass Request;\n\ntypedef Request* RequestPtr;\n\nclass Request : public FastAlloc\n{\n public:\n typedef uint32_t FlagsType;\n typedef ::Flags Flags;\n\n \/** ASI information for this request if it exists. *\/\n static const FlagsType ASI_BITS = 0x000000FF;\n \/** The request was an instruction fetch. *\/\n static const FlagsType INST_FETCH = 0x00000100;\n \/** The virtual address is also the physical address. *\/\n static const FlagsType PHYSICAL = 0x00000200;\n \/** The request is an ALPHA VPTE pal access (hw_ld). *\/\n static const FlagsType VPTE = 0x00000400;\n \/** Use the alternate mode bits in ALPHA. *\/\n static const FlagsType ALTMODE = 0x00000800;\n \/** The request is to an uncacheable address. *\/\n static const FlagsType UNCACHEABLE = 0x00001000;\n \/** This request is to a memory mapped register. *\/\n static const FlagsType MMAPPED_IPR = 0x00002000;\n \/** This request is a clear exclusive. *\/\n static const FlagsType CLEAR_LL = 0x00004000;\n\n \/** The request should not cause a memory access. *\/\n static const FlagsType NO_ACCESS = 0x00080000;\n \/** This request will lock or unlock the accessed memory. When used with\n * a load, the access locks the particular chunk of memory. When used\n * with a store, it unlocks. The rule is that locked accesses have to be\n * made up of a locked load, some operation on the data, and then a locked\n * store.\n *\/\n static const FlagsType LOCKED = 0x00100000;\n \/** The request is a Load locked\/store conditional. *\/\n static const FlagsType LLSC = 0x00200000;\n \/** This request is for a memory swap. *\/\n static const FlagsType MEM_SWAP = 0x00400000;\n static const FlagsType MEM_SWAP_COND = 0x00800000;\n\n \/** The request is a prefetch. *\/\n static const FlagsType PREFETCH = 0x01000000;\n \/** The request should be prefetched into the exclusive state. *\/\n static const FlagsType PF_EXCLUSIVE = 0x02000000;\n \/** The request should be marked as LRU. *\/\n static const FlagsType EVICT_NEXT = 0x04000000;\n\n \/** These flags are *not* cleared when a Request object is reused\n (assigned a new address). *\/\n static const FlagsType STICKY_FLAGS = INST_FETCH;\n\n private:\n typedef uint8_t PrivateFlagsType;\n typedef ::Flags PrivateFlags;\n\n \/** Whether or not the size is valid. *\/\n static const PrivateFlagsType VALID_SIZE = 0x00000001;\n \/** Whether or not paddr is valid (has been written yet). *\/\n static const PrivateFlagsType VALID_PADDR = 0x00000002;\n \/** Whether or not the vaddr & asid are valid. *\/\n static const PrivateFlagsType VALID_VADDR = 0x00000004;\n \/** Whether or not the pc is valid. *\/\n static const PrivateFlagsType VALID_PC = 0x00000010;\n \/** Whether or not the context ID is valid. *\/\n static const PrivateFlagsType VALID_CONTEXT_ID = 0x00000020;\n static const PrivateFlagsType VALID_THREAD_ID = 0x00000040;\n \/** Whether or not the sc result is valid. *\/\n static const PrivateFlagsType VALID_EXTRA_DATA = 0x00000080;\n\n \/** These flags are *not* cleared when a Request object is reused\n (assigned a new address). *\/\n static const PrivateFlagsType STICKY_PRIVATE_FLAGS =\n VALID_CONTEXT_ID | VALID_THREAD_ID;\n\n private:\n \/**\n * The physical address of the request. Valid only if validPaddr\n * is set.\n *\/\n Addr _paddr;\n\n \/**\n * The size of the request. This field must be set when vaddr or\n * paddr is written via setVirt() or setPhys(), so it is always\n * valid as long as one of the address fields is valid.\n *\/\n int _size;\n\n \/** Flag structure for the request. *\/\n Flags _flags;\n\n \/** Private flags for field validity checking. *\/\n PrivateFlags privateFlags;\n\n \/**\n * The time this request was started. Used to calculate\n * latencies. This field is set to curTick() any time paddr or vaddr\n * is written.\n *\/\n Tick _time;\n\n \/** The address space ID. *\/\n int _asid;\n\n \/** The virtual address of the request. *\/\n Addr _vaddr;\n\n \/**\n * Extra data for the request, such as the return value of\n * store conditional or the compare value for a CAS. *\/\n uint64_t _extraData;\n\n \/** The context ID (for statistics, typically). *\/\n int _contextId;\n \/** The thread ID (id within this CPU) *\/\n int _threadId;\n\n \/** program counter of initiating access; for tracing\/debugging *\/\n Addr _pc;\n\n public:\n \/** Minimal constructor. No fields are initialized. \n * (Note that _flags and privateFlags are cleared by Flags\n * default constructor.)\n *\/\n Request()\n {}\n\n \/**\n * Constructor for physical (e.g. device) requests. Initializes\n * just physical address, size, flags, and timestamp (to curTick()).\n * These fields are adequate to perform a request. \n *\/\n Request(Addr paddr, int size, Flags flags)\n {\n setPhys(paddr, size, flags);\n }\n\n Request(Addr paddr, int size, Flags flags, Tick time)\n {\n setPhys(paddr, size, flags, time);\n }\n\n Request(Addr paddr, int size, Flags flags, Tick time, Addr pc)\n {\n setPhys(paddr, size, flags, time);\n privateFlags.set(VALID_PC);\n _pc = pc;\n }\n\n Request(int asid, Addr vaddr, int size, Flags flags, Addr pc,\n int cid, ThreadID tid)\n {\n setVirt(asid, vaddr, size, flags, pc);\n setThreadContext(cid, tid);\n }\n\n ~Request() {} \/\/ for FastAlloc\n\n \/**\n * Set up CPU and thread numbers.\n *\/\n void\n setThreadContext(int context_id, ThreadID tid)\n {\n _contextId = context_id;\n _threadId = tid;\n privateFlags.set(VALID_CONTEXT_ID|VALID_THREAD_ID);\n }\n\n \/**\n * Set up a physical (e.g. device) request in a previously\n * allocated Request object.\n *\/\n void\n setPhys(Addr paddr, int size, Flags flags, Tick time)\n {\n assert(size >= 0);\n _paddr = paddr;\n _size = size;\n _time = time;\n\n _flags.clear(~STICKY_FLAGS);\n _flags.set(flags);\n privateFlags.clear(~STICKY_PRIVATE_FLAGS);\n privateFlags.set(VALID_PADDR|VALID_SIZE);\n }\n\n void\n setPhys(Addr paddr, int size, Flags flags)\n {\n setPhys(paddr, size, flags, curTick());\n }\n\n \/**\n * Set up a virtual (e.g., CPU) request in a previously\n * allocated Request object.\n *\/\n void\n setVirt(int asid, Addr vaddr, int size, Flags flags, Addr pc)\n {\n assert(size >= 0);\n _asid = asid;\n _vaddr = vaddr;\n _size = size;\n _pc = pc;\n _time = curTick();\n\n _flags.clear(~STICKY_FLAGS);\n _flags.set(flags);\n privateFlags.clear(~STICKY_PRIVATE_FLAGS);\n privateFlags.set(VALID_VADDR|VALID_SIZE|VALID_PC);\n }\n\n \/**\n * Set just the physical address. This should only be used to\n * record the result of a translation, and thus the vaddr must be\n * valid before this method is called. Otherwise, use setPhys()\n * to guarantee that the size and flags are also set.\n *\/\n void\n setPaddr(Addr paddr)\n {\n assert(privateFlags.isSet(VALID_VADDR));\n _paddr = paddr;\n privateFlags.set(VALID_PADDR);\n }\n\n \/**\n * Generate two requests as if this request had been split into two\n * pieces. The original request can't have been translated already.\n *\/\n void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2)\n {\n assert(privateFlags.isSet(VALID_VADDR));\n assert(privateFlags.noneSet(VALID_PADDR));\n assert(split_addr > _vaddr && split_addr < _vaddr + _size);\n req1 = new Request;\n *req1 = *this;\n req2 = new Request;\n *req2 = *this;\n req1->_size = split_addr - _vaddr;\n req2->_vaddr = split_addr;\n req2->_size = _size - req1->_size;\n }\n\n \/**\n * Accessor for paddr.\n *\/\n bool\n hasPaddr()\n {\n return privateFlags.isSet(VALID_PADDR);\n }\n\n Addr\n getPaddr()\n {\n assert(privateFlags.isSet(VALID_PADDR));\n return _paddr;\n }\n\n \/**\n * Accessor for size.\n *\/\n bool\n hasSize()\n {\n return privateFlags.isSet(VALID_SIZE);\n }\n\n int\n getSize()\n {\n assert(privateFlags.isSet(VALID_SIZE));\n return _size;\n }\n\n \/** Accessor for time. *\/\n Tick\n time() const\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n return _time;\n }\n\n void\n time(Tick time)\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n _time = time;\n }\n\n \/** Accessor for flags. *\/\n Flags\n getFlags()\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n return _flags;\n }\n\n \/** Note that unlike other accessors, this function sets *specific\n flags* (ORs them in); it does not assign its argument to the\n _flags field. Thus this method should rightly be called\n setFlags() and not just flags(). *\/\n void\n setFlags(Flags flags)\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n _flags.set(flags);\n }\n\n \/** Accessor function for vaddr.*\/\n Addr\n getVaddr()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _vaddr;\n }\n\n \/** Accessor function for asid.*\/\n int\n getAsid()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _asid;\n }\n\n \/** Accessor function for asi.*\/\n uint8_t\n getAsi()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _flags & ASI_BITS;\n }\n\n \/** Accessor function to check if sc result is valid. *\/\n bool\n extraDataValid()\n {\n return privateFlags.isSet(VALID_EXTRA_DATA);\n }\n\n \/** Accessor function for store conditional return value.*\/\n uint64_t\n getExtraData() const\n {\n assert(privateFlags.isSet(VALID_EXTRA_DATA));\n return _extraData;\n }\n\n \/** Accessor function for store conditional return value.*\/\n void\n setExtraData(uint64_t extraData)\n {\n _extraData = extraData;\n privateFlags.set(VALID_EXTRA_DATA);\n }\n\n bool\n hasContextId() const\n {\n return privateFlags.isSet(VALID_CONTEXT_ID);\n }\n\n \/** Accessor function for context ID.*\/\n int\n contextId() const\n {\n assert(privateFlags.isSet(VALID_CONTEXT_ID));\n return _contextId;\n }\n\n \/** Accessor function for thread ID. *\/\n int\n threadId() const\n {\n assert(privateFlags.isSet(VALID_THREAD_ID));\n return _threadId;\n }\n\n bool\n hasPC() const\n {\n return privateFlags.isSet(VALID_PC);\n }\n\n \/** Accessor function for pc.*\/\n Addr\n getPC() const\n {\n assert(privateFlags.isSet(VALID_PC));\n return _pc;\n }\n\n \/** Accessor functions for flags. Note that these are for testing\n only; setting flags should be done via setFlags(). *\/\n bool isUncacheable() const { return _flags.isSet(UNCACHEABLE); }\n bool isInstFetch() const { return _flags.isSet(INST_FETCH); }\n bool isPrefetch() const { return _flags.isSet(PREFETCH); }\n bool isLLSC() const { return _flags.isSet(LLSC); }\n bool isLocked() const { return _flags.isSet(LOCKED); }\n bool isSwap() const { return _flags.isSet(MEM_SWAP|MEM_SWAP_COND); }\n bool isCondSwap() const { return _flags.isSet(MEM_SWAP_COND); }\n bool isMmappedIpr() const { return _flags.isSet(MMAPPED_IPR); }\n bool isClearLL() const { return _flags.isSet(CLEAR_LL); }\n};\n\n#endif \/\/ __MEM_REQUEST_HH__\nMem: Allow ASID to be set after request is created.\/*\n * Copyright (c) 2002-2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ron Dreslinski\n * Steve Reinhardt\n * Ali Saidi\n *\/\n\n\/**\n * @file\n * Declaration of a request, the overall memory request consisting of\n the parts of the request that are persistent throughout the transaction.\n *\/\n\n#ifndef __MEM_REQUEST_HH__\n#define __MEM_REQUEST_HH__\n\n#include \n\n#include \"base\/fast_alloc.hh\"\n#include \"base\/flags.hh\"\n#include \"base\/misc.hh\"\n#include \"base\/types.hh\"\n#include \"sim\/core.hh\"\n\nclass Request;\n\ntypedef Request* RequestPtr;\n\nclass Request : public FastAlloc\n{\n public:\n typedef uint32_t FlagsType;\n typedef ::Flags Flags;\n\n \/** ASI information for this request if it exists. *\/\n static const FlagsType ASI_BITS = 0x000000FF;\n \/** The request was an instruction fetch. *\/\n static const FlagsType INST_FETCH = 0x00000100;\n \/** The virtual address is also the physical address. *\/\n static const FlagsType PHYSICAL = 0x00000200;\n \/** The request is an ALPHA VPTE pal access (hw_ld). *\/\n static const FlagsType VPTE = 0x00000400;\n \/** Use the alternate mode bits in ALPHA. *\/\n static const FlagsType ALTMODE = 0x00000800;\n \/** The request is to an uncacheable address. *\/\n static const FlagsType UNCACHEABLE = 0x00001000;\n \/** This request is to a memory mapped register. *\/\n static const FlagsType MMAPPED_IPR = 0x00002000;\n \/** This request is a clear exclusive. *\/\n static const FlagsType CLEAR_LL = 0x00004000;\n\n \/** The request should not cause a memory access. *\/\n static const FlagsType NO_ACCESS = 0x00080000;\n \/** This request will lock or unlock the accessed memory. When used with\n * a load, the access locks the particular chunk of memory. When used\n * with a store, it unlocks. The rule is that locked accesses have to be\n * made up of a locked load, some operation on the data, and then a locked\n * store.\n *\/\n static const FlagsType LOCKED = 0x00100000;\n \/** The request is a Load locked\/store conditional. *\/\n static const FlagsType LLSC = 0x00200000;\n \/** This request is for a memory swap. *\/\n static const FlagsType MEM_SWAP = 0x00400000;\n static const FlagsType MEM_SWAP_COND = 0x00800000;\n\n \/** The request is a prefetch. *\/\n static const FlagsType PREFETCH = 0x01000000;\n \/** The request should be prefetched into the exclusive state. *\/\n static const FlagsType PF_EXCLUSIVE = 0x02000000;\n \/** The request should be marked as LRU. *\/\n static const FlagsType EVICT_NEXT = 0x04000000;\n\n \/** These flags are *not* cleared when a Request object is reused\n (assigned a new address). *\/\n static const FlagsType STICKY_FLAGS = INST_FETCH;\n\n private:\n typedef uint8_t PrivateFlagsType;\n typedef ::Flags PrivateFlags;\n\n \/** Whether or not the size is valid. *\/\n static const PrivateFlagsType VALID_SIZE = 0x00000001;\n \/** Whether or not paddr is valid (has been written yet). *\/\n static const PrivateFlagsType VALID_PADDR = 0x00000002;\n \/** Whether or not the vaddr & asid are valid. *\/\n static const PrivateFlagsType VALID_VADDR = 0x00000004;\n \/** Whether or not the pc is valid. *\/\n static const PrivateFlagsType VALID_PC = 0x00000010;\n \/** Whether or not the context ID is valid. *\/\n static const PrivateFlagsType VALID_CONTEXT_ID = 0x00000020;\n static const PrivateFlagsType VALID_THREAD_ID = 0x00000040;\n \/** Whether or not the sc result is valid. *\/\n static const PrivateFlagsType VALID_EXTRA_DATA = 0x00000080;\n\n \/** These flags are *not* cleared when a Request object is reused\n (assigned a new address). *\/\n static const PrivateFlagsType STICKY_PRIVATE_FLAGS =\n VALID_CONTEXT_ID | VALID_THREAD_ID;\n\n private:\n \/**\n * The physical address of the request. Valid only if validPaddr\n * is set.\n *\/\n Addr _paddr;\n\n \/**\n * The size of the request. This field must be set when vaddr or\n * paddr is written via setVirt() or setPhys(), so it is always\n * valid as long as one of the address fields is valid.\n *\/\n int _size;\n\n \/** Flag structure for the request. *\/\n Flags _flags;\n\n \/** Private flags for field validity checking. *\/\n PrivateFlags privateFlags;\n\n \/**\n * The time this request was started. Used to calculate\n * latencies. This field is set to curTick() any time paddr or vaddr\n * is written.\n *\/\n Tick _time;\n\n \/** The address space ID. *\/\n int _asid;\n\n \/** The virtual address of the request. *\/\n Addr _vaddr;\n\n \/**\n * Extra data for the request, such as the return value of\n * store conditional or the compare value for a CAS. *\/\n uint64_t _extraData;\n\n \/** The context ID (for statistics, typically). *\/\n int _contextId;\n \/** The thread ID (id within this CPU) *\/\n int _threadId;\n\n \/** program counter of initiating access; for tracing\/debugging *\/\n Addr _pc;\n\n public:\n \/** Minimal constructor. No fields are initialized. \n * (Note that _flags and privateFlags are cleared by Flags\n * default constructor.)\n *\/\n Request()\n {}\n\n \/**\n * Constructor for physical (e.g. device) requests. Initializes\n * just physical address, size, flags, and timestamp (to curTick()).\n * These fields are adequate to perform a request. \n *\/\n Request(Addr paddr, int size, Flags flags)\n {\n setPhys(paddr, size, flags);\n }\n\n Request(Addr paddr, int size, Flags flags, Tick time)\n {\n setPhys(paddr, size, flags, time);\n }\n\n Request(Addr paddr, int size, Flags flags, Tick time, Addr pc)\n {\n setPhys(paddr, size, flags, time);\n privateFlags.set(VALID_PC);\n _pc = pc;\n }\n\n Request(int asid, Addr vaddr, int size, Flags flags, Addr pc,\n int cid, ThreadID tid)\n {\n setVirt(asid, vaddr, size, flags, pc);\n setThreadContext(cid, tid);\n }\n\n ~Request() {} \/\/ for FastAlloc\n\n \/**\n * Set up CPU and thread numbers.\n *\/\n void\n setThreadContext(int context_id, ThreadID tid)\n {\n _contextId = context_id;\n _threadId = tid;\n privateFlags.set(VALID_CONTEXT_ID|VALID_THREAD_ID);\n }\n\n \/**\n * Set up a physical (e.g. device) request in a previously\n * allocated Request object.\n *\/\n void\n setPhys(Addr paddr, int size, Flags flags, Tick time)\n {\n assert(size >= 0);\n _paddr = paddr;\n _size = size;\n _time = time;\n\n _flags.clear(~STICKY_FLAGS);\n _flags.set(flags);\n privateFlags.clear(~STICKY_PRIVATE_FLAGS);\n privateFlags.set(VALID_PADDR|VALID_SIZE);\n }\n\n void\n setPhys(Addr paddr, int size, Flags flags)\n {\n setPhys(paddr, size, flags, curTick());\n }\n\n \/**\n * Set up a virtual (e.g., CPU) request in a previously\n * allocated Request object.\n *\/\n void\n setVirt(int asid, Addr vaddr, int size, Flags flags, Addr pc)\n {\n assert(size >= 0);\n _asid = asid;\n _vaddr = vaddr;\n _size = size;\n _pc = pc;\n _time = curTick();\n\n _flags.clear(~STICKY_FLAGS);\n _flags.set(flags);\n privateFlags.clear(~STICKY_PRIVATE_FLAGS);\n privateFlags.set(VALID_VADDR|VALID_SIZE|VALID_PC);\n }\n\n \/**\n * Set just the physical address. This should only be used to\n * record the result of a translation, and thus the vaddr must be\n * valid before this method is called. Otherwise, use setPhys()\n * to guarantee that the size and flags are also set.\n *\/\n void\n setPaddr(Addr paddr)\n {\n assert(privateFlags.isSet(VALID_VADDR));\n _paddr = paddr;\n privateFlags.set(VALID_PADDR);\n }\n\n \/**\n * Generate two requests as if this request had been split into two\n * pieces. The original request can't have been translated already.\n *\/\n void splitOnVaddr(Addr split_addr, RequestPtr &req1, RequestPtr &req2)\n {\n assert(privateFlags.isSet(VALID_VADDR));\n assert(privateFlags.noneSet(VALID_PADDR));\n assert(split_addr > _vaddr && split_addr < _vaddr + _size);\n req1 = new Request;\n *req1 = *this;\n req2 = new Request;\n *req2 = *this;\n req1->_size = split_addr - _vaddr;\n req2->_vaddr = split_addr;\n req2->_size = _size - req1->_size;\n }\n\n \/**\n * Accessor for paddr.\n *\/\n bool\n hasPaddr()\n {\n return privateFlags.isSet(VALID_PADDR);\n }\n\n Addr\n getPaddr()\n {\n assert(privateFlags.isSet(VALID_PADDR));\n return _paddr;\n }\n\n \/**\n * Accessor for size.\n *\/\n bool\n hasSize()\n {\n return privateFlags.isSet(VALID_SIZE);\n }\n\n int\n getSize()\n {\n assert(privateFlags.isSet(VALID_SIZE));\n return _size;\n }\n\n \/** Accessor for time. *\/\n Tick\n time() const\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n return _time;\n }\n\n void\n time(Tick time)\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n _time = time;\n }\n\n \/** Accessor for flags. *\/\n Flags\n getFlags()\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n return _flags;\n }\n\n \/** Note that unlike other accessors, this function sets *specific\n flags* (ORs them in); it does not assign its argument to the\n _flags field. Thus this method should rightly be called\n setFlags() and not just flags(). *\/\n void\n setFlags(Flags flags)\n {\n assert(privateFlags.isSet(VALID_PADDR|VALID_VADDR));\n _flags.set(flags);\n }\n\n \/** Accessor function for vaddr.*\/\n Addr\n getVaddr()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _vaddr;\n }\n\n \/** Accessor function for asid.*\/\n int\n getAsid()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _asid;\n }\n\n \/** Accessor function for asid.*\/\n void\n setAsid(int asid)\n {\n _asid = asid;\n }\n\n \/** Accessor function for asi.*\/\n uint8_t\n getAsi()\n {\n assert(privateFlags.isSet(VALID_VADDR));\n return _flags & ASI_BITS;\n }\n\n \/** Accessor function to check if sc result is valid. *\/\n bool\n extraDataValid()\n {\n return privateFlags.isSet(VALID_EXTRA_DATA);\n }\n\n \/** Accessor function for store conditional return value.*\/\n uint64_t\n getExtraData() const\n {\n assert(privateFlags.isSet(VALID_EXTRA_DATA));\n return _extraData;\n }\n\n \/** Accessor function for store conditional return value.*\/\n void\n setExtraData(uint64_t extraData)\n {\n _extraData = extraData;\n privateFlags.set(VALID_EXTRA_DATA);\n }\n\n bool\n hasContextId() const\n {\n return privateFlags.isSet(VALID_CONTEXT_ID);\n }\n\n \/** Accessor function for context ID.*\/\n int\n contextId() const\n {\n assert(privateFlags.isSet(VALID_CONTEXT_ID));\n return _contextId;\n }\n\n \/** Accessor function for thread ID. *\/\n int\n threadId() const\n {\n assert(privateFlags.isSet(VALID_THREAD_ID));\n return _threadId;\n }\n\n bool\n hasPC() const\n {\n return privateFlags.isSet(VALID_PC);\n }\n\n \/** Accessor function for pc.*\/\n Addr\n getPC() const\n {\n assert(privateFlags.isSet(VALID_PC));\n return _pc;\n }\n\n \/** Accessor functions for flags. Note that these are for testing\n only; setting flags should be done via setFlags(). *\/\n bool isUncacheable() const { return _flags.isSet(UNCACHEABLE); }\n bool isInstFetch() const { return _flags.isSet(INST_FETCH); }\n bool isPrefetch() const { return _flags.isSet(PREFETCH); }\n bool isLLSC() const { return _flags.isSet(LLSC); }\n bool isLocked() const { return _flags.isSet(LOCKED); }\n bool isSwap() const { return _flags.isSet(MEM_SWAP|MEM_SWAP_COND); }\n bool isCondSwap() const { return _flags.isSet(MEM_SWAP_COND); }\n bool isMmappedIpr() const { return _flags.isSet(MMAPPED_IPR); }\n bool isClearLL() const { return _flags.isSet(CLEAR_LL); }\n};\n\n#endif \/\/ __MEM_REQUEST_HH__\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \"xbt.h\"\n#include \"simgrid\/s4u.hpp\"\n\n#include \"rsg\/services.hpp\"\n#include \"rsg\/Server.hpp\"\n#include \"common.hpp\"\n\n\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\n\nusing boost::shared_ptr;\nusing namespace ::simgrid;\n\nstd::vector threads;\n\nXBT_LOG_NEW_CATEGORY(RSG_THRIFT, \"Remote SimGrid\");\nXBT_LOG_NEW_DEFAULT_SUBCATEGORY(RSG_THRIFT_SERVER, RSG_THRIFT , \"RSG server (Remote SimGrid)\");\n\n\/* Fork a remote process, and serve it until it CMD_QUITs *\/\nstatic int rsg_representative(int argc, char **argv) {\n debug_server_print(\"START\");\n if (! fork()) {\n int newargc = argc-1+2+1;\n char **newargv = (char**)calloc(newargc, sizeof(char*));\n newargv[0] = (char*)\"\/usr\/bin\/env\";\n newargv[1] = (char*)\"--\";\n for(int i=1; i < argc; i++) {\n newargv[1+i] = argv[i];\n }\n newargv[newargc-1] = NULL;\n debug_server_print(\"fork+exec: %s\", newargv[2]);\n execv(newargv[0], newargv);\n }\n debug_server_print(\"RUN server\");\n SocketServer &socketServer = SocketServer::getSocketServer();\n RsgThriftServerFramework *server = socketServer.acceptClient();\n server->serve();\n delete server;\n debug_server_print(\"END\");\n return 0;\n}\n\nint main(int argc, char **argv) {\n \n SocketServer &socketServer = SocketServer::createSocketServer(std::string(\"127.0.0.1\"), 9090);\n socketServer.connect();\n \n s4u::Engine *e = new s4u::Engine(&argc,argv);\n \n if (argc < 3) {\n fprintf(stderr,\"Usage: rsg platform.xml deploy.xml port\\n\");\n exit(1);\n }\n \n \/* Initialize the SimGrid world *\/\n e->loadPlatform(argv[1]);\n e->registerDefault(rsg_representative);\n e->loadDeployment(argv[2]);\n e->run();\n \n socketServer.closeServer();\n return 0;\n}\nActor from deployement file can connects with an env variable#include \n#include \n#include \n\n#include \n\n#include \"xbt.h\"\n#include \"simgrid\/s4u.hpp\"\n\n#include \"rsg\/Socket.hpp\"\n#include \"rsg\/services.hpp\"\n#include \"rsg\/Server.hpp\"\n#include \"common.hpp\"\n\n\nusing namespace ::apache::thrift;\nusing namespace ::apache::thrift::protocol;\nusing namespace ::apache::thrift::transport;\nusing namespace ::apache::thrift::server;\n\nusing boost::shared_ptr;\nusing namespace ::simgrid;\n\nstd::vector threads;\n\nXBT_LOG_NEW_CATEGORY(RSG_THRIFT, \"Remote SimGrid\");\nXBT_LOG_NEW_DEFAULT_SUBCATEGORY(RSG_THRIFT_SERVER, RSG_THRIFT , \"RSG server (Remote SimGrid)\");\n\n\/*!\n * Fork a remote process, creates an RPC server to handle all the actor communication\n * The function first creates an RPC server with an unused TCP port. When the server is succefully setted in listen mode \n * the function forks and set the Rpc port to the environment with execve. \n*\/\nstatic int rsg_representative(int argc, char **argv) {\n debug_server_print(\"START\");\n \n \/\/First we create an RPC server designed to communicate with the futur child\n int rpcPort = getFreePort(1024);\n bool connected = false;\n \n RsgThriftServerFramework* server = NULL;\n do {\n server = SocketServer::getSocketServer().createRpcServer(rpcPort);\n try {\n server->listen();\n connected = true;\n } catch(apache::thrift::transport::TTransportException &ex) {\n rpcPort = getFreePort(1024);\n delete server;\n } \n } while( ! connected);\n \n \/\/ We fork the actor process\n if (! fork()) {\n \/\/We create the string formated to environment variables (key=value)\n std::string envKeyValueStr, envKeyName = \"RsgRpcPort\";\n std::string envValue = std::to_string(rpcPort);\n envKeyValueStr = envKeyName + \"=\" + envValue;\n \n \/\/ Initialization of the array desgnied to host the new environment variables\n int envp_size = 2; \n char **newenviron = (char**) malloc(sizeof(char*) * envp_size);\n newenviron[0] = (char*) malloc(sizeof(char) * (envKeyValueStr.size() + 1));\n \n \/\/ Copying the new key value string\n strcpy(newenviron[0], envKeyValueStr.c_str());\n \/\/ Null terminating of the array\n newenviron[1] = NULL;\n \n int newargc = argc-1+2+1;\n char **newargv = (char**)calloc(newargc, sizeof(char*));\n newargv[0] = (char*)\"\/usr\/bin\/env\";\n newargv[1] = (char*)\"--\";\n for(int i=1; i < argc; i++) {\n newargv[1+i] = argv[i];\n }\n newargv[newargc-1] = NULL;\n debug_server_print(\"fork+exec: %s\", newargv[2]);\n execve(newargv[0], newargv, newenviron);\n }\n\n server->serve();\n delete server;\n debug_server_print(\"END\");\n return 0;\n}\n\nint main(int argc, char **argv) {\n \n SocketServer &socketServer = SocketServer::createSocketServer(std::string(\"127.0.0.1\"), 9090);\n socketServer.connect();\n \n s4u::Engine *e = new s4u::Engine(&argc,argv);\n \n if (argc < 3) {\n fprintf(stderr,\"Usage: rsg platform.xml deploy.xml port\\n\");\n exit(1);\n }\n \n \/* Initialize the SimGrid world *\/\n e->loadPlatform(argv[1]);\n e->registerDefault(rsg_representative);\n e->loadDeployment(argv[2]);\n e->run();\n \n socketServer.closeServer();\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"read_line.hpp\"\n#include \n\nstatic void on_unknown(const std::string& command)\n{\n std::cout << \"unknown message:\" << command << std::endl;\n}\n\nstatic void on_update(const bc::payment_address& address,\n size_t height, const bc::hash_digest& blk_hash,\n const bc::transaction_type&)\n{\n std::cout << \"update:\" << address.encoded() << std::endl;\n}\n\n\/**\n * A dynamically-allocated structure holding the resources needed for a\n * connection to a bitcoin server.\n *\/\nclass connection\n{\npublic:\n connection(zmq::context_t& context, const std::string& server)\n : socket(context, server), codec(socket, on_update, on_unknown)\n {\n }\n\n libbitcoin::client::zmq_socket socket;\n libbitcoin::client::obelisk_codec codec;\n};\n\n\/**\n * Command-line interface for talking to the oblelisk server.\n *\/\nclass cli\n{\npublic:\n ~cli();\n cli();\n\n int run();\n\nprivate:\n void command();\n void cmd_exit();\n void cmd_help();\n void cmd_connect(std::stringstream& args);\n void cmd_disconnect(std::stringstream& args);\n void cmd_height(std::stringstream& args);\n\n bool check_connection();\n bool read_string(std::stringstream& args, std::string& out,\n const std::string& error_message);\n\n bool done_;\n\n zmq::context_t context_;\n read_line terminal_;\n connection *connection_;\n};\n\ncli::~cli()\n{\n delete connection_;\n}\n\ncli::cli()\n : done_(false), terminal_(context_), connection_(nullptr)\n{\n}\n\n\/**\n * The main loop for the example application. This loop can be woken up\n * by either events from the network or by input from the terminal.\n *\/\nint cli::run()\n{\n std::cout << \"type \\\"help\\\" for instructions\" << std::endl;\n terminal_.show_prompt();\n\n while (!done_)\n {\n std::vector items;\n items.reserve(2);\n items.push_back(terminal_.pollitem());\n if (connection_)\n items.push_back(connection_->socket.pollitem());\n zmq::poll(items.data(), items.size(), -1);\n\n if (items[0].revents)\n command();\n if (connection_ && items[1].revents)\n connection_->socket.forward(connection_->codec);\n }\n return 0;\n}\n\n\/**\n * Reads a command from the terminal thread, and processes it appropriately.\n *\/\nvoid cli::command()\n{\n std::stringstream reader(terminal_.get_line());\n std::string command;\n reader >> command;\n\n if (command == \"exit\") cmd_exit();\n else if (command == \"help\") cmd_help();\n else if (command == \"connect\") cmd_connect(reader);\n else if (command == \"disconnect\") cmd_disconnect(reader);\n else if (command == \"height\") cmd_height(reader);\n else\n std::cout << \"unknown command \" << command << std::endl;\n\n \/\/ Display another prompt, if needed:\n if (!done_)\n terminal_.show_prompt();\n}\n\nvoid cli::cmd_exit()\n{\n done_ = true;\n}\n\nvoid cli::cmd_help()\n{\n std::cout << \"commands:\" << std::endl;\n std::cout << \" exit - leave the program\" << std::endl;\n std::cout << \" help - this menu\" << std::endl;\n std::cout << \" connect - connect to a server\" << std::endl;\n std::cout << \" disconnect - disconnect from the server\" << std::endl;\n std::cout << \" height - get last block height\" << std::endl;\n}\n\nvoid cli::cmd_connect(std::stringstream& args)\n{\n std::string server;\n if (!read_string(args, server, \"error: no server given\"))\n return;\n std::cout << \"connecting to \" << server << std::endl;\n\n delete connection_;\n connection_ = nullptr;\n try\n {\n connection_ = new connection(context_, server);\n }\n catch (zmq::error_t)\n {\n std::cout << \"error: failed to connect\" << std::endl;\n }\n}\n\nvoid cli::cmd_disconnect(std::stringstream& args)\n{\n if (!check_connection())\n return;\n delete connection_;\n connection_ = nullptr;\n}\n\nstatic void on_error(const std::error_code& ec)\n{\n std::cout << \"error: \" << ec.message() << std::endl;\n}\n\nvoid cli::cmd_height(std::stringstream& args)\n{\n if (!check_connection())\n return;\n\n auto handler = [](size_t height)\n {\n std::cout << \"height: \" << height << std::endl;\n };\n connection_->codec.fetch_last_height(on_error, handler);\n}\n\n\/**\n * Verifies that a connection exists, and prints an error message otherwise.\n *\/\nbool cli::check_connection()\n{\n if (!connection_)\n {\n std::cout << \"error: no connection\" << std::endl;\n return false;\n }\n return true;\n}\n\n\/**\n * Parses a string argument out of the command line,\n * or prints an error message if there is none.\n *\/\nbool cli::read_string(std::stringstream& args, std::string& out,\n const std::string& error_message)\n{\n args >> out;\n if (!out.size())\n {\n std::cout << error_message << std::endl;\n return false;\n }\n return true;\n}\n\nint main()\n{\n cli c;\n return c.run();\n}\nexamples: Add history command#include \n#include \n#include \n#include \n#include \"read_line.hpp\"\n#include \n\nstatic void on_unknown(const std::string& command)\n{\n std::cout << \"unknown message:\" << command << std::endl;\n}\n\nstatic void on_update(const bc::payment_address& address,\n size_t height, const bc::hash_digest& blk_hash,\n const bc::transaction_type&)\n{\n std::cout << \"update:\" << address.encoded() << std::endl;\n}\n\n\/**\n * A dynamically-allocated structure holding the resources needed for a\n * connection to a bitcoin server.\n *\/\nclass connection\n{\npublic:\n connection(zmq::context_t& context, const std::string& server)\n : socket(context, server), codec(socket, on_update, on_unknown)\n {\n }\n\n libbitcoin::client::zmq_socket socket;\n libbitcoin::client::obelisk_codec codec;\n};\n\n\/**\n * Command-line interface for talking to the oblelisk server.\n *\/\nclass cli\n{\npublic:\n ~cli();\n cli();\n\n int run();\n\nprivate:\n void command();\n void cmd_exit();\n void cmd_help();\n void cmd_connect(std::stringstream& args);\n void cmd_disconnect(std::stringstream& args);\n void cmd_height(std::stringstream& args);\n void cmd_history(std::stringstream& args);\n\n bool check_connection();\n bool read_string(std::stringstream& args, std::string& out,\n const std::string& error_message);\n bool read_address(std::stringstream& args, bc::payment_address& out);\n\n bool done_;\n\n zmq::context_t context_;\n read_line terminal_;\n connection *connection_;\n};\n\ncli::~cli()\n{\n delete connection_;\n}\n\ncli::cli()\n : done_(false), terminal_(context_), connection_(nullptr)\n{\n}\n\n\/**\n * The main loop for the example application. This loop can be woken up\n * by either events from the network or by input from the terminal.\n *\/\nint cli::run()\n{\n std::cout << \"type \\\"help\\\" for instructions\" << std::endl;\n terminal_.show_prompt();\n\n while (!done_)\n {\n std::vector items;\n items.reserve(2);\n items.push_back(terminal_.pollitem());\n if (connection_)\n items.push_back(connection_->socket.pollitem());\n zmq::poll(items.data(), items.size(), -1);\n\n if (items[0].revents)\n command();\n if (connection_ && items[1].revents)\n connection_->socket.forward(connection_->codec);\n }\n return 0;\n}\n\n\/**\n * Reads a command from the terminal thread, and processes it appropriately.\n *\/\nvoid cli::command()\n{\n std::stringstream reader(terminal_.get_line());\n std::string command;\n reader >> command;\n\n if (command == \"exit\") cmd_exit();\n else if (command == \"help\") cmd_help();\n else if (command == \"connect\") cmd_connect(reader);\n else if (command == \"disconnect\") cmd_disconnect(reader);\n else if (command == \"height\") cmd_height(reader);\n else if (command == \"history\") cmd_history(reader);\n else\n std::cout << \"unknown command \" << command << std::endl;\n\n \/\/ Display another prompt, if needed:\n if (!done_)\n terminal_.show_prompt();\n}\n\nvoid cli::cmd_exit()\n{\n done_ = true;\n}\n\nvoid cli::cmd_help()\n{\n std::cout << \"commands:\" << std::endl;\n std::cout << \" exit - leave the program\" << std::endl;\n std::cout << \" help - this menu\" << std::endl;\n std::cout << \" connect - connect to a server\" << std::endl;\n std::cout << \" disconnect - disconnect from the server\" << std::endl;\n std::cout << \" height - get last block height\" << std::endl;\n std::cout << \" history
- get an address' history\" << std::endl;\n}\n\nvoid cli::cmd_connect(std::stringstream& args)\n{\n std::string server;\n if (!read_string(args, server, \"error: no server given\"))\n return;\n std::cout << \"connecting to \" << server << std::endl;\n\n delete connection_;\n connection_ = nullptr;\n try\n {\n connection_ = new connection(context_, server);\n }\n catch (zmq::error_t)\n {\n std::cout << \"error: failed to connect\" << std::endl;\n }\n}\n\nvoid cli::cmd_disconnect(std::stringstream& args)\n{\n if (!check_connection())\n return;\n delete connection_;\n connection_ = nullptr;\n}\n\nstatic void on_error(const std::error_code& ec)\n{\n std::cout << \"error: \" << ec.message() << std::endl;\n}\n\nvoid cli::cmd_height(std::stringstream& args)\n{\n if (!check_connection())\n return;\n\n auto handler = [](size_t height)\n {\n std::cout << \"height: \" << height << std::endl;\n };\n connection_->codec.fetch_last_height(on_error, handler);\n}\n\nvoid cli::cmd_history(std::stringstream& args)\n{\n if (!check_connection())\n return;\n bc::payment_address address;\n if (!read_address(args, address))\n return;\n\n auto handler = [](const bc::blockchain::history_list& history)\n {\n for (auto row: history)\n std::cout << row.value << std::endl;\n };\n connection_->codec.address_fetch_history(on_error, handler, address);\n}\n\n\/**\n * Verifies that a connection exists, and prints an error message otherwise.\n *\/\nbool cli::check_connection()\n{\n if (!connection_)\n {\n std::cout << \"error: no connection\" << std::endl;\n return false;\n }\n return true;\n}\n\n\/**\n * Parses a string argument out of the command line,\n * or prints an error message if there is none.\n *\/\nbool cli::read_string(std::stringstream& args, std::string& out,\n const std::string& error_message)\n{\n args >> out;\n if (!out.size())\n {\n std::cout << error_message << std::endl;\n return false;\n }\n return true;\n}\n\n\/**\n * Reads a bitcoin address from the command-line, or prints an error if\n * the address is missing or invalid.\n *\/\nbool cli::read_address(std::stringstream& args, bc::payment_address& out)\n{\n std::string address;\n if (!read_string(args, address, \"error: no address given\"))\n return false;\n if (!out.set_encoded(address))\n {\n std::cout << \"error: invalid address \" << address << std::endl;\n return false;\n }\n return true;\n}\n\nint main()\n{\n cli c;\n return c.run();\n}\n<|endoftext|>"} {"text":"\/\/ Make use of the CMake build system or compile manually, e.g. with:\r\n\/\/ g++ -std=c++11 example.cc -lsweep\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\nint main(int argc, char* argv[]) try {\r\n if (argc != 2) {\r\n std::cerr << \"Usage: .\/example-c++ device\\n\";\r\n return EXIT_FAILURE;\r\n }\r\n\r\n std::cout << \"Constructing sweep device...\" << std::endl;\r\n neo::neo device{argv[1]};\r\n\r\n std::cout << \"Motor Speed Setting: \" << device.get_motor_speed()\r\n << \" Hz\" << std::endl;\r\n\/\/ std::cout << \"Sample Rate Setting: \" << device.get_sample_rate()\r\n\/\/ << \" Hz\" << std::endl;\r\n\r\n std::cout << \"Beginning data acquisition as soon as motor speed stabilizes...\"\r\n << std::endl;\r\n device.start_scanning();\r\n\r\n for (auto n = 0; n < 10; ++n) {\r\n const neo::scan scan = device.get_scan();\r\n\r\n std::cout << \"Scan #\" << n << \":\" << std::endl;\r\n for (const neo::sample& sample : scan.samples) {\r\n std::cout << \"angle \" << sample.angle << \" distance \"\r\n << sample.distance << std::endl;\r\n \/\/<< \" strength \" << sample.signal_strength << \"\\n\";\r\n }\r\n }\r\n\r\n device.stop_scanning();\r\n} catch (const neo::device_error& e) {\r\n std::cerr << \"Error: \" << e.what() << std::endl;\r\n}\r\n\r\nfix(example baudrate): adding baudrate to example.\/\/ Make use of the CMake build system or compile manually, e.g. with:\r\n\/\/ g++ -std=c++11 example.cc -lsweep\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\nint main(int argc, char* argv[]) try {\r\n if (argc != 3) {\r\n std::cerr << \"Usage: .\/example-c++ device baudrate\\n\";\r\n return EXIT_FAILURE;\r\n }\r\n\r\n std::cout << \"Constructing sweep device...\" << std::endl;\r\n neo::neo device{argv[1], atoi(argv[2])};\r\n\r\n std::cout << \"Motor Speed Setting: \" << device.get_motor_speed()\r\n << \" Hz\" << std::endl;\r\n\/\/ std::cout << \"Sample Rate Setting: \" << device.get_sample_rate()\r\n\/\/ << \" Hz\" << std::endl;\r\n\r\n std::cout << \"Beginning data acquisition as soon as motor speed stabilizes...\"\r\n << std::endl;\r\n device.start_scanning();\r\n\r\n for (auto n = 0; n < 10; ++n) {\r\n const neo::scan scan = device.get_scan();\r\n\r\n std::cout << \"Scan #\" << n << \":\" << std::endl;\r\n for (const neo::sample& sample : scan.samples) {\r\n std::cout << \"angle \" << sample.angle << \" distance \"\r\n << sample.distance << std::endl;\r\n \/\/<< \" strength \" << sample.signal_strength << \"\\n\";\r\n }\r\n }\r\n\r\n device.stop_scanning();\r\n} catch (const neo::device_error& e) {\r\n std::cerr << \"Error: \" << e.what() << std::endl;\r\n}\r\n\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"SuMo.h\"\n#include \"Timer.h\"\n\n\/* specific to file *\/\nconst int NUM_ARGS = 4;\nconst char* filename = \"logData\";\nconst char* description = \"log data from DAQ\";\nusing namespace std;\n\/********************\/\n\n\/* subtract pedestal values on-line *\/\nstatic bool PED_SUBTRCT = false;\n\nstatic int LIMIT_READOUT_RATE = 6000; \/\/usecs limit between event polling\nstatic int NUM_SEQ_TIMEOUTS = 100; \/\/ number of sequential timeouts before ending run\nconst float MAX_INT_TIMER = 800.; \/\/ max cpu timer before ending run (secs)\n\/* note: usb timeout defined in include\/stdUSB.h *\/\n\nbool overwriteExistingFile = false;\n\nint main(int argc, char* argv[]){\n if(argc == 2 && std::string(argv[1]) == \"-h\"){\n cout << endl;\n cout << filename << \" :: \" << description << endl;\n cout << filename << \" :: takes \" << NUM_ARGS-1 << \" arguments\" << endl;\n return 1;\n }\n else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){\n cout << \"error: too many number of arguments\" << endl;\n return -1;\n }\n else{\n int num_checks = 5;\n int num_events = 100;\n SuMo command;\n char log_data_filename[100];\n\n strcpy(log_data_filename, argv[1]);\n num_events = atoi(argv[2]);\n int trig_mode = atoi(argv[3]);\n\n if(command.check_active_boards(num_checks))\n return 1;\n\n\n vector events = command.get_data(num_events, trig_mode, 0);\n command.log_data(log_data_filename, events, trig_mode);\n\n return 0;\n }\n}\n\n\nvector SuMo::get_data(unsigned int NUM_READS, int trig_mode, int acq_rate){\n\n int check_event;\n int asic_baseline[psecSampleCells];\n int count = 0;\n int psec_cnt = 0;\n int last_k;\n float _now_, t = 0.;\n char logDataFilename[300];\n Timer timer = Timer();\n time_t now;\n unsigned short sample;\n int* Meta;\n\n vector event_data;\n\n \/\/ read all front end cards\n bool all[numFrontBoards];\n for(int i = 0; i < numFrontBoards; i++) all[i] = true;\n\n load_ped();\n\n int number_of_frontend_cards = 0;\n\n for( int board = 0; board < numFrontBoards; board++){\n if(DC_ACTIVE[board]) number_of_frontend_cards++;\n\n }\n\n cout << \"--------------------------------------------------------------\" << endl;\n cout << \"number of front-end boards detected = \" << number_of_frontend_cards\n << \" of \" << numFrontBoards << \" address slots in system\" << endl;\n cout << \"Trying for \" << NUM_READS << \" events logged to disk, in a timeout window of \"\n << MAX_INT_TIMER << \" seconds\" << endl;\n cout << \"--------------------------------------------------------------\" << endl << endl;\n\n usleep(100000);\n\n \/* cpu time zero *\/\n timer.start();\n\n bool reset_event = true;\n\n \/\/ set read mode to NULL\n set_usb_read_mode(0);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(0);\n system_card_trig_valid(false);\n if(mode==USB2x) system_slave_card_trig_valid(false);\n\n \/\/check system trigger number\n read_CC(false, false, 100);\n int board_trigger= CC_EVENT_COUNT_FROMCC0;\n int last_board_trigger = board_trigger;\n\n for(int k=0; k MAX_INT_TIMER) {\n cout << endl << \"readout timed out at \" << t << \"on event \" << k << endl;\n break;\n }\n\n \/\/ trig_mode = 1 is external source or PSEC4 self trigger\n \/\/ trig_mode = 0 is over software (USB), i.e. calibration logging\n if(trig_mode == 0){\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n\n \/\/ 'rate-only' mode, only pull data every second\n if(trig_mode == 2) usleep(3e6);\n\n prep_sync();\n if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);\n software_trigger((unsigned int) 15);\n make_sync();\n\n \/\/acq rate limit\n usleep(LIMIT_READOUT_RATE); \/\/ somewhat arbitrary hard-coded rate limitation\n \/\/system_card_trig_valid(false);\n \/\/if(mode == USB2x) system_slave_card_trig_valid(false);\n }\n else{\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n usleep(100);\n for(int iii=0; iii<2; iii++){\n system_card_trig_valid(false);\n if(mode==USB2x) system_slave_card_trig_valid(false);\n }\n\n \/\/send in trig 'valid' signal\n sys_wait(100);\n prep_sync();\n if(mode==USB2x) system_slave_card_trig_valid(true);\n system_card_trig_valid(true);\n make_sync();\n \/\/}\n \/\/acq rate limit\n usleep(acq_rate+LIMIT_READOUT_RATE);\n }\n int num_pulls = 0;\n int evts = 0;\n int digs = 0;\n while(board_trigger==last_board_trigger && t < MAX_INT_TIMER){\n\n read_CC(false, false, 100);\n board_trigger = CC_EVENT_COUNT_FROMCC0;\n cout << \"waiting for trigger... on system event: \"\n << board_trigger << \" & readout attempt \" << k\n << \" @time \" << t << \" \\r\";\n cout.flush();\n usleep(1000);\n t = timer.stop();\n num_pulls++;\n if(num_pulls > 100) break;\n \/\/if(num_pulls > 10) break; \/\/use this is board trigger does not iterate\n }\n\n last_board_trigger = board_trigger;\n if(mode == USB2x) system_slave_card_trig_valid(false);\n system_card_trig_valid(false);\n \/\/set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);\n evts = read_CC(false, false, 0);\n for(int chkdig=0; chkdig 0){\n psec_cnt = 0;\n \/\/ assign meta data\n Meta=get_AC_info(false, targetAC, false,k, t, t, evts);\n\n check_event = 0;\n\n for(int i = 0; i < AC_CHANNELS; i++){\n if(i>0 && i % 6 == 0) psec_cnt ++;\n\n for(int j = 0; j < psecSampleCells; j++){\n sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];\n if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];\n\n adcDat[targetAC]->Data[i][j] = (unsigned int) sample;\n }\n }\n \/* wraparound_correction, if desired: *\/\n int baseline[psecSampleCells];\n unwrap_baseline(baseline, 2);\n for (int j = 0; j < psecSampleCells; j++){\n asic_baseline[j] = baseline[j];\n adcDat[targetAC]->Data[AC_CHANNELS][j] = Meta[j];\n }\n }\n \/\/if timeout on only some, but not all boards\n else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] && DC_ACTIVE[targetAC]){\n for(int i = 0; i < AC_CHANNELS; i++){\n if(i>0 && i % 6 == 0) psec_cnt ++;\n\n for(int j = 0; j < psecSampleCells; j++){\n sample = 0xFF;\n adcDat[targetAC]->Data[i][j] = sample;\n }\n }\n for(int j = 0; j < psecSampleCells; j++){\n adcDat[targetAC]->Data[AC_CHANNELS][j] =0;\n }\n }\n }\n event_data.push_back(adcDat);\n\n\n last_k = k;\n }\n\n cout << endl;\n cout << \"Done on readout: \" << last_k+1 << \" :: @time \" << t << \" sec\" << endl;\n\n cleanup();\n\n\n dump_data();\n\n return event_data;\n}\n\nint SuMo::log_data(const char* log_filename, vector event_data, int trig_mode){\n int asic_baseline[psecSampleCells];\n float _now_, t = 0.;\n Timer timer = Timer();\n time_t now;\n int last_k;\n char logDataFilename[300];\n \/\/ 'scalar' mode\n ofstream rate_fs;\n if(trig_mode == 2){\n char logRateFilename[300];\n sprintf(logRateFilename, \"%s.rate.dat\", log_filename);\n rate_fs.open(logRateFilename, ios::trunc);\n }\n\n \/\/ full waveform, standard mode\n time(&now);\n char timestring[100];\n strftime(timestring, 80, \"%Y-%m-%d-%H-%M\", localtime(&now));\n \/\/ sprintf(logDataFilename, \"%s-%s.acdc.dat\", timestring, log_filename);\n sprintf(logDataFilename, \"%s.dat\", log_filename);\n\n \/\/ check if file exists, inquire whether to overwrite\n \/\/ shouldn't be an issue now since file timestamped in filename ^^\n string temp;\n while(fileExists(logDataFilename)){\n cout << \"file already exists, try new filename: (or enter to overwrite \/ ctrl-C to quit): \";\n getline(cin, temp);\n if(temp.empty()) break;\n sprintf(logDataFilename, \"%s.dat\", temp.c_str());\n }\n\n ofstream ofs;\n ofs.open(logDataFilename, ios::trunc);\n\n \/\/ save pedestal data to file header for reference, easy access\n \/\/ zero pad to match data format\n\n\n \/* wraparound_correction, if desired: *\/\n int baseline[psecSampleCells];\n unwrap_baseline(baseline, 2);\n for (int j = 0; j < psecSampleCells; j++){\n asic_baseline[j] = baseline[j];\n }\n\n \/* Create header *\/\n char delim = ' ';\n ofs << \"Event\" << delim << \"Board\" << delim << \"Sample\";\n for(int c=1; c <= AC_CHANNELS; c++){\n ofs << delim << \"Ch\" << c;\n }\n ofs << delim << endl;\n\n \/* Record events *\/\n \/\/ For each event\n for(int event = 0; event < event_data.size(); event++){\n packet_t** events = event_data[event];\n \/\/ For each board\n for (int board = 0; board < numFrontBoards; board++){\n if (!DC_ACTIVE[board]) continue;\n \/\/ For each channels\n for (int ch = 0; ch < AC_CHANNELS; ch++){\n ofs << event << delim << board << delim << ch;\n \/\/ For each sample\n for (int i = 0; i < psecSampleCells; i++) {\n int ped_subtracted = events[board]->Data[ch][i] - PED_DATA[board][ch][i];\n ofs << delim << dec << ped_subtracted; \/\/ std::dec\n }\n ofs << endl;\n }\n\n }\n\n if(trig_mode == 2){\n for(int board=0; boardself_trig_scalar[channel] << \"\\t\";\n\n rate_fs << endl;\n }\n }\n }\n }\n last_k = event;\n }\n\n cout << endl;\n cout << \"Done on readout: \" << last_k+1 << \" :: @time \" <wrong header labels#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"SuMo.h\"\n#include \"Timer.h\"\n\n\/* specific to file *\/\nconst int NUM_ARGS = 4;\nconst char* filename = \"logData\";\nconst char* description = \"log data from DAQ\";\nusing namespace std;\n\/********************\/\n\n\/* subtract pedestal values on-line *\/\nstatic bool PED_SUBTRCT = false;\n\nstatic int LIMIT_READOUT_RATE = 6000; \/\/usecs limit between event polling\nstatic int NUM_SEQ_TIMEOUTS = 100; \/\/ number of sequential timeouts before ending run\nconst float MAX_INT_TIMER = 800.; \/\/ max cpu timer before ending run (secs)\n\/* note: usb timeout defined in include\/stdUSB.h *\/\n\nbool overwriteExistingFile = false;\n\nint main(int argc, char* argv[]){\n if(argc == 2 && std::string(argv[1]) == \"-h\"){\n cout << endl;\n cout << filename << \" :: \" << description << endl;\n cout << filename << \" :: takes \" << NUM_ARGS-1 << \" arguments\" << endl;\n return 1;\n }\n else if(argc > NUM_ARGS+1 || argc < NUM_ARGS){\n cout << \"error: too many number of arguments\" << endl;\n return -1;\n }\n else{\n int num_checks = 5;\n int num_events = 100;\n SuMo command;\n char log_data_filename[100];\n\n strcpy(log_data_filename, argv[1]);\n num_events = atoi(argv[2]);\n int trig_mode = atoi(argv[3]);\n\n if(command.check_active_boards(num_checks))\n return 1;\n\n\n vector events = command.get_data(num_events, trig_mode, 0);\n command.log_data(log_data_filename, events, trig_mode);\n\n return 0;\n }\n}\n\n\nvector SuMo::get_data(unsigned int NUM_READS, int trig_mode, int acq_rate){\n\n int check_event;\n int asic_baseline[psecSampleCells];\n int count = 0;\n int psec_cnt = 0;\n int last_k;\n float _now_, t = 0.;\n char logDataFilename[300];\n Timer timer = Timer();\n time_t now;\n unsigned short sample;\n int* Meta;\n\n vector event_data;\n\n \/\/ read all front end cards\n bool all[numFrontBoards];\n for(int i = 0; i < numFrontBoards; i++) all[i] = true;\n\n load_ped();\n\n int number_of_frontend_cards = 0;\n\n for( int board = 0; board < numFrontBoards; board++){\n if(DC_ACTIVE[board]) number_of_frontend_cards++;\n\n }\n\n cout << \"--------------------------------------------------------------\" << endl;\n cout << \"number of front-end boards detected = \" << number_of_frontend_cards\n << \" of \" << numFrontBoards << \" address slots in system\" << endl;\n cout << \"Trying for \" << NUM_READS << \" events logged to disk, in a timeout window of \"\n << MAX_INT_TIMER << \" seconds\" << endl;\n cout << \"--------------------------------------------------------------\" << endl << endl;\n\n usleep(100000);\n\n \/* cpu time zero *\/\n timer.start();\n\n bool reset_event = true;\n\n \/\/ set read mode to NULL\n set_usb_read_mode(0);\n if(mode==USB2x) set_usb_read_mode_slaveDevice(0);\n system_card_trig_valid(false);\n if(mode==USB2x) system_slave_card_trig_valid(false);\n\n \/\/check system trigger number\n read_CC(false, false, 100);\n int board_trigger= CC_EVENT_COUNT_FROMCC0;\n int last_board_trigger = board_trigger;\n\n for(int k=0; k MAX_INT_TIMER) {\n cout << endl << \"readout timed out at \" << t << \"on event \" << k << endl;\n break;\n }\n\n \/\/ trig_mode = 1 is external source or PSEC4 self trigger\n \/\/ trig_mode = 0 is over software (USB), i.e. calibration logging\n if(trig_mode == 0){\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n\n \/\/ 'rate-only' mode, only pull data every second\n if(trig_mode == 2) usleep(3e6);\n\n prep_sync();\n if(mode == USB2x) software_trigger_slaveDevice((unsigned int)15);\n software_trigger((unsigned int) 15);\n make_sync();\n\n \/\/acq rate limit\n usleep(LIMIT_READOUT_RATE); \/\/ somewhat arbitrary hard-coded rate limitation\n \/\/system_card_trig_valid(false);\n \/\/if(mode == USB2x) system_slave_card_trig_valid(false);\n }\n else{\n manage_cc_fifo(1);\n if(mode==USB2x) manage_cc_fifo_slaveDevice(1);\n usleep(100);\n for(int iii=0; iii<2; iii++){\n system_card_trig_valid(false);\n if(mode==USB2x) system_slave_card_trig_valid(false);\n }\n\n \/\/send in trig 'valid' signal\n sys_wait(100);\n prep_sync();\n if(mode==USB2x) system_slave_card_trig_valid(true);\n system_card_trig_valid(true);\n make_sync();\n \/\/}\n \/\/acq rate limit\n usleep(acq_rate+LIMIT_READOUT_RATE);\n }\n int num_pulls = 0;\n int evts = 0;\n int digs = 0;\n while(board_trigger==last_board_trigger && t < MAX_INT_TIMER){\n\n read_CC(false, false, 100);\n board_trigger = CC_EVENT_COUNT_FROMCC0;\n cout << \"waiting for trigger... on system event: \"\n << board_trigger << \" & readout attempt \" << k\n << \" @time \" << t << \" \\r\";\n cout.flush();\n usleep(1000);\n t = timer.stop();\n num_pulls++;\n if(num_pulls > 100) break;\n \/\/if(num_pulls > 10) break; \/\/use this is board trigger does not iterate\n }\n\n last_board_trigger = board_trigger;\n if(mode == USB2x) system_slave_card_trig_valid(false);\n system_card_trig_valid(false);\n \/\/set_usb_read_mode_slaveDevice(0), set_usb_read_mode(0);\n evts = read_CC(false, false, 0);\n for(int chkdig=0; chkdig 0){\n psec_cnt = 0;\n \/\/ assign meta data\n Meta=get_AC_info(false, targetAC, false,k, t, t, evts);\n\n check_event = 0;\n\n for(int i = 0; i < AC_CHANNELS; i++){\n if(i>0 && i % 6 == 0) psec_cnt ++;\n\n for(int j = 0; j < psecSampleCells; j++){\n sample = adcDat[targetAC]->AC_RAW_DATA[psec_cnt][i%6*256+j];\n if(PED_SUBTRCT) sample -= PED_DATA[targetAC][i][j];\n\n adcDat[targetAC]->Data[i][j] = (unsigned int) sample;\n }\n }\n \/* wraparound_correction, if desired: *\/\n int baseline[psecSampleCells];\n unwrap_baseline(baseline, 2);\n for (int j = 0; j < psecSampleCells; j++){\n asic_baseline[j] = baseline[j];\n adcDat[targetAC]->Data[AC_CHANNELS][j] = Meta[j];\n }\n }\n \/\/if timeout on only some, but not all boards\n else if( numBoards > 0 && BOARDS_TIMEOUT[targetAC] && DC_ACTIVE[targetAC]){\n for(int i = 0; i < AC_CHANNELS; i++){\n if(i>0 && i % 6 == 0) psec_cnt ++;\n\n for(int j = 0; j < psecSampleCells; j++){\n sample = 0xFF;\n adcDat[targetAC]->Data[i][j] = sample;\n }\n }\n for(int j = 0; j < psecSampleCells; j++){\n adcDat[targetAC]->Data[AC_CHANNELS][j] =0;\n }\n }\n }\n event_data.push_back(adcDat);\n\n\n last_k = k;\n }\n\n cout << endl;\n cout << \"Done on readout: \" << last_k+1 << \" :: @time \" << t << \" sec\" << endl;\n\n cleanup();\n\n\n dump_data();\n\n return event_data;\n}\n\nint SuMo::log_data(const char* log_filename, vector event_data, int trig_mode){\n int asic_baseline[psecSampleCells];\n float _now_, t = 0.;\n Timer timer = Timer();\n time_t now;\n int last_k;\n char logDataFilename[300];\n \/\/ 'scalar' mode\n ofstream rate_fs;\n if(trig_mode == 2){\n char logRateFilename[300];\n sprintf(logRateFilename, \"%s.rate\", log_filename);\n rate_fs.open(logRateFilename, ios::trunc);\n }\n\n \/\/ full waveform, standard mode\n time(&now);\n char timestring[100];\n strftime(timestring, 80, \"%Y-%m-%d-%H-%M\", localtime(&now));\n \/\/ sprintf(logDataFilename, \"%s-%s.acdc.dat\", timestring, log_filename);\n sprintf(logDataFilename, \"%s.acdc\", log_filename);\n\n \/\/ check if file exists, inquire whether to overwrite\n \/\/ shouldn't be an issue now since file timestamped in filename ^^\n string temp;\n while(fileExists(logDataFilename)){\n cout << \"file already exists, try new filename: (or enter to overwrite \/ ctrl-C to quit): \";\n getline(cin, temp);\n if(temp.empty()) break;\n sprintf(logDataFilename, \"%s.acdc\", temp.c_str());\n }\n\n ofstream ofs;\n ofs.open(logDataFilename, ios::trunc);\n\n \/\/ save pedestal data to file header for reference, easy access\n \/\/ zero pad to match data format\n\n\n \/* wraparound_correction, if desired: *\/\n int baseline[psecSampleCells];\n unwrap_baseline(baseline, 2);\n for (int j = 0; j < psecSampleCells; j++){\n asic_baseline[j] = baseline[j];\n }\n\n \/* Create header *\/\n char delim = ' ';\n ofs << \"Event\" << delim << \"Board\" << delim << \"Channel\" << delim << \"Samples\" << endl;\n\n \/* Record events *\/\n \/\/ For each event\n for(int event = 0; event < event_data.size(); event++){\n packet_t** events = event_data[event];\n \/\/ For each board\n for (int board = 0; board < numFrontBoards; board++){\n if (!DC_ACTIVE[board]) continue;\n \/\/ For each channels\n for (int ch = 0; ch < AC_CHANNELS; ch++){\n ofs << event << delim << board << delim << ch + 1;\n \/\/ For each sample\n for (int i = 0; i < psecSampleCells; i++) {\n int ped_subtracted = events[board]->Data[ch][i] - PED_DATA[board][ch][i];\n ofs << delim << dec << ped_subtracted; \/\/ std::dec\n }\n ofs << endl;\n }\n\n }\n\n if(trig_mode == 2){\n for(int board=0; boardself_trig_scalar[channel] << \"\\t\";\n\n rate_fs << endl;\n }\n }\n }\n }\n last_k = event;\n }\n\n cout << endl;\n cout << \"Done on readout: \" << last_k+1 << \" :: @time \" <"} {"text":"\/\/\/\n\/\/\/ @file P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function. P2(x, y) counts the\n\/\/\/ numbers <= x that have exactly 2 prime factors\n\/\/\/ each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Count the primes inside [prime, stop]\ntemplate \nint64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)\n{\n int64_t count = 0;\n\n for (; prime <= stop; count++)\n prime = it.next_prime();\n\n return count;\n}\n\n\/\/\/ Calculate the thread sieving distance. The idea is to\n\/\/\/ gradually increase the thread_distance in order to\n\/\/\/ keep all CPU cores busy.\n\/\/\/\nvoid balanceLoad(int64_t* thread_distance, \n int64_t low,\n int64_t z,\n int threads,\n double start_time)\n{\n double seconds = get_wtime() - start_time;\n\n int64_t min_distance = 1 << 23;\n int64_t max_distance = ceil_div(z - low, threads);\n\n if (seconds < 60)\n *thread_distance *= 2;\n if (seconds > 60)\n *thread_distance \/= 2;\n\n *thread_distance = in_between(min_distance, *thread_distance, max_distance);\n}\n\ntemplate \nT P2_OpenMP_thread(T x,\n int64_t y,\n int64_t z,\n int64_t thread_distance,\n int64_t thread_num,\n int64_t low,\n int64_t& pix,\n int64_t& pix_count)\n{\n pix = 0;\n pix_count = 0;\n low += thread_distance * thread_num;\n z = min(low + thread_distance, z);\n int64_t start = (int64_t) max(x \/ z, y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n primesieve::iterator rit(stop + 1, start);\n primesieve::iterator it(low - 1, z);\n\n int64_t next = it.next_prime();\n int64_t prime = rit.prev_prime();\n T P2_thread = 0;\n\n \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n while (prime > start &&\n x \/ prime < z)\n {\n pix += count_primes(it, next, x \/ prime);\n P2_thread += pix;\n pix_count++;\n prime = rit.prev_prime();\n }\n\n pix += count_primes(it, next, z - 1);\n\n return P2_thread;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime.\n\/\/\/ Memory usage: O(z^(1\/2))\n\/\/\/\ntemplate \nT P2_mpi_master(T x, int64_t y, int threads)\n{\n static_assert(prt::is_signed::value,\n \"P2(T x, ...): T must be signed integer type\");\n\n if (x < 4)\n return 0;\n\n T a = pi_legendre(y, threads);\n T b = pi_legendre((int64_t) isqrt(x), threads);\n\n if (a >= b)\n return 0;\n\n int64_t low = 2;\n int64_t z = (int64_t)(x \/ max(y, 1));\n int64_t min_distance = 1 << 23;\n int64_t thread_distance = min_distance;\n\n int proc_id = mpi_proc_id();\n int procs = mpi_num_procs();\n\n int64_t distance = z - low;\n int64_t proc_distance = ceil_div(distance, procs);\n low += proc_distance * proc_id;\n z = min(low + proc_distance, z);\n\n T p2 = 0;\n T pix_total = pi_legendre(low - 1, threads);\n\n if (is_mpi_master_proc())\n p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n aligned_vector pix(threads);\n aligned_vector pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n while (low < z)\n {\n int64_t max_threads = ceil_div(z - low, thread_distance);\n threads = in_between(1, threads, max_threads);\n double time = get_wtime();\n\n #pragma omp parallel for num_threads(threads) reduction(+: p2)\n for (int i = 0; i < threads; i++)\n p2 += P2_OpenMP_thread(x, y, z, thread_distance, i, low, pix[i], pix_counts[i]);\n\n low += thread_distance * threads;\n balanceLoad(&thread_distance, low, z, threads, time);\n\n \/\/ add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n p2 += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (is_print())\n {\n double percent = get_percent(low, z);\n cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n << percent << '%' << flush;\n }\n }\n\n p2 = mpi_reduce_sum(p2);\n\n return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int64_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int128_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#endif\n\n} \/\/ namespace\nRefactor\/\/\/\n\/\/\/ @file P2_mpi.cpp\n\/\/\/ @brief 2nd partial sieve function. P2(x, y) counts the\n\/\/\/ numbers <= x that have exactly 2 prime factors\n\/\/\/ each exceeding the a-th prime.\n\/\/\/\n\/\/\/ Copyright (C) 2017 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n #include \n#endif\n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\n\/\/\/ Count the primes inside [prime, stop]\ntemplate \nint64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop)\n{\n int64_t count = 0;\n\n for (; prime <= stop; count++)\n prime = it.next_prime();\n\n return count;\n}\n\n\/\/\/ Calculate the thread sieving distance. The idea is to\n\/\/\/ gradually increase the thread_distance in order to\n\/\/\/ keep all CPU cores busy.\n\/\/\/\nvoid balanceLoad(int64_t* thread_distance, \n int64_t low,\n int64_t z,\n int threads,\n double start_time)\n{\n double seconds = get_wtime() - start_time;\n\n int64_t min_distance = 1 << 23;\n int64_t max_distance = ceil_div(z - low, threads);\n\n if (seconds < 60)\n *thread_distance *= 2;\n if (seconds > 60)\n *thread_distance \/= 2;\n\n *thread_distance = in_between(min_distance, *thread_distance, max_distance);\n}\n\ntemplate \nT P2_thread(T x,\n int64_t y,\n int64_t z,\n int64_t low,\n int64_t thread_num,\n int64_t thread_distance,\n int64_t& pix,\n int64_t& pix_count)\n{\n pix = 0;\n pix_count = 0;\n low += thread_distance * thread_num;\n z = min(low + thread_distance, z);\n int64_t start = (int64_t) max(x \/ z, y);\n int64_t stop = (int64_t) min(x \/ low, isqrt(x));\n\n primesieve::iterator rit(stop + 1, start);\n primesieve::iterator it(low - 1, z);\n\n int64_t next = it.next_prime();\n int64_t prime = rit.prev_prime();\n T p2 = 0;\n\n \/\/ \\sum_{i = pi[start]+1}^{pi[stop]} pi(x \/ primes[i])\n while (prime > start &&\n x \/ prime < z)\n {\n pix += count_primes(it, next, x \/ prime);\n p2 += pix;\n pix_count++;\n prime = rit.prev_prime();\n }\n\n pix += count_primes(it, next, z - 1);\n\n return p2;\n}\n\n\/\/\/ P2(x, y) counts the numbers <= x that have exactly 2\n\/\/\/ prime factors each exceeding the a-th prime.\n\/\/\/ Memory usage: O(z^(1\/2))\n\/\/\/\ntemplate \nT P2_mpi_master(T x, int64_t y, int threads)\n{\n static_assert(prt::is_signed::value,\n \"P2(T x, ...): T must be signed integer type\");\n\n if (x < 4)\n return 0;\n\n T a = pi_legendre(y, threads);\n T b = pi_legendre((int64_t) isqrt(x), threads);\n\n if (a >= b)\n return 0;\n\n int64_t low = 2;\n int64_t z = (int64_t)(x \/ max(y, 1));\n int64_t min_distance = 1 << 23;\n int64_t thread_distance = min_distance;\n\n int proc_id = mpi_proc_id();\n int procs = mpi_num_procs();\n\n int64_t distance = z - low;\n int64_t proc_distance = ceil_div(distance, procs);\n low += proc_distance * proc_id;\n z = min(low + proc_distance, z);\n\n T p2 = 0;\n T pix_total = pi_legendre(low - 1, threads);\n\n if (is_mpi_master_proc())\n p2 = (a - 2) * (a + 1) \/ 2 - (b - 2) * (b + 1) \/ 2;\n\n aligned_vector pix(threads);\n aligned_vector pix_counts(threads);\n\n \/\/ \\sum_{i=a+1}^{b} pi(x \/ primes[i])\n while (low < z)\n {\n int64_t max_threads = ceil_div(z - low, thread_distance);\n threads = in_between(1, threads, max_threads);\n double time = get_wtime();\n\n #pragma omp parallel for num_threads(threads) reduction(+: p2)\n for (int i = 0; i < threads; i++)\n p2 += P2_thread(x, y, z, low, i, thread_distance, pix[i], pix_counts[i]);\n\n low += thread_distance * threads;\n balanceLoad(&thread_distance, low, z, threads, time);\n\n \/\/ add missing sum contributions in order\n for (int i = 0; i < threads; i++)\n {\n p2 += pix_total * pix_counts[i];\n pix_total += pix[i];\n }\n\n if (is_print())\n {\n double percent = get_percent(low, z);\n cout << \"\\rStatus: \" << fixed << setprecision(get_status_precision(x))\n << percent << '%' << flush;\n }\n }\n\n p2 = mpi_reduce_sum(p2);\n\n return p2;\n}\n\n} \/\/ namespace\n\nnamespace primecount {\n\nint64_t P2_mpi(int64_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int64_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#ifdef HAVE_INT128_T\n\nint128_t P2_mpi(int128_t x, int64_t y, int threads)\n{\n print(\"\");\n print(\"=== P2_mpi(x, y) ===\");\n print(\"Computation of the 2nd partial sieve function\");\n print(x, y, threads);\n\n double time = get_wtime();\n int128_t p2 = P2_mpi_master(x, y, threads);\n\n print(\"P2\", p2, time);\n return p2;\n}\n\n#endif\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \"mmc.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int maxCheck = 16000000;\nconst int smallestGap = 500000;\n\nbool isPrime(int);\nint primeCalc(int[]);\nvoid recvWork(int[], int);\nvoid sendWork(int[], int, MPI_Request*);\nvoid receiveSendResults(MMC_Manager&);\nint receiveResults(MMC_Manager& manager);\nint fillGaps(int*, MMC_Manager&);\nbool incrementWorkUnit(int[], int, int);\nvoid worker_function(MMC_Machine&);\nvoid middle_manager_function(MMC_Machine&);\nvoid top_manager_function(MMC_Machine&);\n\nint main(void) {\n MPI_Init(NULL, NULL);\n Layout_t layout = read_cluster_layout_from_file();\n MPI_Barrier(MPI_COMM_WORLD);\n \n MMC_Machine machine(layout);\n \n if (machine.role() == \"worker\") {\n worker_function(machine);\n }\n else {\n if (machine.is_top()) {\n top_manager_function(machine);\n }\n else {\n middle_manager_function(machine);\n }\n }\n \n MPI_Finalize();\n return 0;\n}\n\nbool isPrime(int n) {\n int sqRoot = sqrt(n);\n for (int i = 2; i <= sqRoot; ++i) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n}\n\nint primeCalc(int workInfo[]) {\n int total = 0;\n for (int i = workInfo[0]; i <= workInfo[1]; i += 2) {\n if (isPrime(i)) {\n ++total;\n }\n }\n return total;\n}\n\nvoid recvWork(int workInfo[], int commRank) {\n MPI_Recv(workInfo, 2, MPI_INT, commRank, WORK_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n}\n\nvoid sendWork(int workInfo[], int commRank, MPI_Request* request) {\n MPI_Isend(workInfo, 2, MPI_INT, commRank, WORK_TAG, MPI_COMM_WORLD, request);\n}\n\nvoid receiveSendResults(MMC_Manager& manager) {\n int total = receiveResults(manager);\n MPI_Send(&total, 1, MPI_INT, manager.manager_rank(), RESULTS_TAG, MPI_COMM_WORLD);\n}\n\nint receiveResults(MMC_Manager& manager) {\n int total = 0, recvTemp;\n int start = manager.first_worker(), end = manager.last_worker();\n for (int i = start; i <= end; ++i) {\n MPI_Recv(&recvTemp, 1, MPI_INT, i, RESULTS_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n total += recvTemp;\n }\n return total;\n}\n\nint fillGaps(int* gaps, MMC_Manager& manager) {\n int numLayers = (manager.layout()).size();\n gaps[0] = 0;\n gaps[1] = smallestGap;\n for (int i = 2; i < numLayers; ++i) {\n int sizeLower = (manager.layout())[i - 1].size();\n int sizeCurr = (manager.layout())[i].size();\n int multiplier = sizeLower \/ sizeCurr;\n gaps[i] = gaps[i - 1] * multiplier;\n }\n return gaps[manager.level()];\n}\n\nbool incrementWorkUnit(int workInfo[], int gapToUse, int workEnd) {\n if (workInfo[1] == workEnd) {\n return true;\n }\n else {\n workInfo[0] += gapToUse;\n workInfo[1] = workInfo[0] + gapToUse - 1;\n if (workInfo[1] > workEnd) {\n workInfo[1] = workEnd;\n }\n }\n return false;\n}\n\nvoid worker_function(MMC_Machine& machine) {\n<<<<<<< HEAD\n MMC_Worker worker(machine);\n=======\n MMC_Worker worker;\n worker = machine;\n>>>>>>> origin\/master\n int managerRank = worker.manager_rank();\n int workInfo[2];\n int primeCount = 0;\n \n bool hasMoreWork = worker.get_more_work();\n while (hasMoreWork) {\n recvWork(workInfo, managerRank);\n primeCount += primeCalc(workInfo);\n hasMoreWork = worker.get_more_work();\n }\n MPI_Send(&primeCount, 1, MPI_INT, managerRank, RESULTS_TAG, MPI_COMM_WORLD);\n}\n\nvoid middle_manager_function(MMC_Machine& machine) {\n<<<<<<< HEAD\n MMC_Manager manager(machine);\n=======\n MMC_Manager manager;\n manager = machine;\n>>>>>>> origin\/master\n int* gaps = new int[(manager.layout()).size()];\n int gapToUse = fillGaps(gaps, manager);\n \n int workEnd;\n int workInfo[2];\n int managerRank = manager.manager_rank();\n MPI_Request requestDummy;\n bool hasMoreWork = manager.get_more_work();\n while (hasMoreWork) {\n recvWork(workInfo, managerRank);\n workEnd = workInfo[1];\n workInfo[1] = workInfo[0] + gapToUse - 1;\n \n bool isDone = false;\n while (!isDone) {\n int nextRank = manager.next_worker();\n \n sendWork(workInfo, nextRank, &requestDummy);\n \n isDone = incrementWorkUnit(workInfo, gapToUse, workEnd);\n }\n hasMoreWork = manager.get_more_work();\n }\n delete[] (gaps);\n manager.clear_worker_queue();\n receiveSendResults(manager);\n}\n\nvoid top_manager_function(MMC_Machine& machine) {\n double startTime = omp_get_wtime();\n<<<<<<< HEAD\n MMC_Manager manager(machine);\n=======\n MMC_Manager manager;\n manager = machine;\n>>>>>>> origin\/master\n int* gaps = new int[(manager.layout()).size()];\n int gapToUse = fillGaps(gaps, manager);\n \n int workStart = 3, workEnd = maxCheck;\n int workInfo[2] = {workStart, workStart + (gapToUse -1)};\n MPI_Request requestDummy;\n bool isDone = false;\n while (!isDone) {\n int nextRank = manager.next_worker();\n \n sendWork(workInfo, nextRank, &requestDummy);\n \n isDone = incrementWorkUnit(workInfo, gapToUse, workEnd);\n }\n manager.clear_worker_queue();\n \n int totalPrimes = receiveResults(manager);\n ++totalPrimes;\n \n double endTime = omp_get_wtime();\n cout << totalPrimes << \" primes found in \" << endTime - startTime << \" seconds.\" << endl;\n}\nUpdate primes.cpp#include \"mmc.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nconst int maxCheck = 16000000;\nconst int smallestGap = 500000;\n\nbool isPrime(int);\nint primeCalc(int[]);\nvoid recvWork(int[], int);\nvoid sendWork(int[], int, MPI_Request*);\nvoid receiveSendResults(MMC_Manager&);\nint receiveResults(MMC_Manager& manager);\nint fillGaps(int*, MMC_Manager&);\nbool incrementWorkUnit(int[], int, int);\nvoid worker_function(MMC_Machine&);\nvoid middle_manager_function(MMC_Machine&);\nvoid top_manager_function(MMC_Machine&);\n\nint main(void) {\n MPI_Init(NULL, NULL);\n Layout_t layout = read_cluster_layout_from_file();\n MPI_Barrier(MPI_COMM_WORLD);\n \n MMC_Machine machine(layout);\n \n if (machine.role() == \"worker\") {\n worker_function(machine);\n }\n else {\n if (machine.is_top()) {\n top_manager_function(machine);\n }\n else {\n middle_manager_function(machine);\n }\n }\n \n MPI_Finalize();\n return 0;\n}\n\nbool isPrime(int n) {\n int sqRoot = sqrt(n);\n for (int i = 2; i <= sqRoot; ++i) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n}\n\nint primeCalc(int workInfo[]) {\n int total = 0;\n for (int i = workInfo[0]; i <= workInfo[1]; i += 2) {\n if (isPrime(i)) {\n ++total;\n }\n }\n return total;\n}\n\nvoid recvWork(int workInfo[], int commRank) {\n MPI_Recv(workInfo, 2, MPI_INT, commRank, WORK_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n}\n\nvoid sendWork(int workInfo[], int commRank, MPI_Request* request) {\n MPI_Isend(workInfo, 2, MPI_INT, commRank, WORK_TAG, MPI_COMM_WORLD, request);\n}\n\nvoid receiveSendResults(MMC_Manager& manager) {\n int total = receiveResults(manager);\n MPI_Send(&total, 1, MPI_INT, manager.manager_rank(), RESULTS_TAG, MPI_COMM_WORLD);\n}\n\nint receiveResults(MMC_Manager& manager) {\n int total = 0, recvTemp;\n int start = manager.first_worker(), end = manager.last_worker();\n for (int i = start; i <= end; ++i) {\n MPI_Recv(&recvTemp, 1, MPI_INT, i, RESULTS_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);\n total += recvTemp;\n }\n return total;\n}\n\nint fillGaps(int* gaps, MMC_Manager& manager) {\n int numLayers = (manager.layout()).size();\n gaps[0] = 0;\n gaps[1] = smallestGap;\n for (int i = 2; i < numLayers; ++i) {\n int sizeLower = (manager.layout())[i - 1].size();\n int sizeCurr = (manager.layout())[i].size();\n int multiplier = sizeLower \/ sizeCurr;\n gaps[i] = gaps[i - 1] * multiplier;\n }\n return gaps[manager.level()];\n}\n\nbool incrementWorkUnit(int workInfo[], int gapToUse, int workEnd) {\n if (workInfo[1] == workEnd) {\n return true;\n }\n else {\n workInfo[0] += gapToUse;\n workInfo[1] = workInfo[0] + gapToUse - 1;\n if (workInfo[1] > workEnd) {\n workInfo[1] = workEnd;\n }\n }\n return false;\n}\n\nvoid worker_function(MMC_Machine& machine) {\n MMC_Worker worker(machine);\n int managerRank = worker.manager_rank();\n int workInfo[2];\n int primeCount = 0;\n \n bool hasMoreWork = worker.get_more_work();\n while (hasMoreWork) {\n recvWork(workInfo, managerRank);\n primeCount += primeCalc(workInfo);\n hasMoreWork = worker.get_more_work();\n }\n MPI_Send(&primeCount, 1, MPI_INT, managerRank, RESULTS_TAG, MPI_COMM_WORLD);\n}\n\nvoid middle_manager_function(MMC_Machine& machine) {\n MMC_Manager manager(machine);\n int* gaps = new int[(manager.layout()).size()];\n int gapToUse = fillGaps(gaps, manager);\n \n int workEnd;\n int workInfo[2];\n int managerRank = manager.manager_rank();\n MPI_Request requestDummy;\n bool hasMoreWork = manager.get_more_work();\n while (hasMoreWork) {\n recvWork(workInfo, managerRank);\n workEnd = workInfo[1];\n workInfo[1] = workInfo[0] + gapToUse - 1;\n \n bool isDone = false;\n while (!isDone) {\n int nextRank = manager.next_worker();\n \n sendWork(workInfo, nextRank, &requestDummy);\n \n isDone = incrementWorkUnit(workInfo, gapToUse, workEnd);\n }\n hasMoreWork = manager.get_more_work();\n }\n delete[] (gaps);\n manager.clear_worker_queue();\n receiveSendResults(manager);\n}\n\nvoid top_manager_function(MMC_Machine& machine) {\n double startTime = omp_get_wtime();\n MMC_Manager manager(machine);\n int* gaps = new int[(manager.layout()).size()];\n int gapToUse = fillGaps(gaps, manager);\n \n int workStart = 3, workEnd = maxCheck;\n int workInfo[2] = {workStart, workStart + (gapToUse -1)};\n MPI_Request requestDummy;\n bool isDone = false;\n while (!isDone) {\n int nextRank = manager.next_worker();\n \n sendWork(workInfo, nextRank, &requestDummy);\n \n isDone = incrementWorkUnit(workInfo, gapToUse, workEnd);\n }\n manager.clear_worker_queue();\n \n int totalPrimes = receiveResults(manager);\n ++totalPrimes;\n \n double endTime = omp_get_wtime();\n cout << totalPrimes << \" primes found in \" << endTime - startTime << \" seconds.\" << endl;\n}\n<|endoftext|>"} {"text":"#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n QString line = name;\n if( count > 1 ) {\n line += QString( \" (x%1)\" ).arg( count );\n }\n\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, line );\n painter.resetTransform();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, int titleFontSize, int rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPixelSize( titleFontSize );\n mTitleFont.setPixelSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Window );\n setAttribute( Qt::WA_TranslucentBackground );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n LoadCards();\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid Overlay::LoadCards() {\n QFile file( \":\/data\/cards.json\" );\n bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );\n assert( opened );\n\n QByteArray jsonData = file.readAll();\n QJsonParseError error;\n QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();\n assert( error.error == QJsonParseError::NoError );\n\n mCardDB.clear();\n\n for( QJsonValueRef jsonCardRef : jsonCards ) {\n QJsonObject jsonCard = jsonCardRef.toObject();\n mCardDB[ jsonCard[\"id\"].toString() ] = jsonCard.toVariantMap();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n int overlayWidth = 200;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n OverlayHistoryWindow wnd( \"Cards drawn\", mPlayerHistory, overlayWidth, 10, 10, 12, 12 );\n PaintHistoryInScreen( painter, wnd, mPlayerDeckRect.topRight() + QPoint( 20, 0 ) );\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n OverlayHistoryWindow wnd( \"Cards played by opponent\", mOpponentHistory, overlayWidth, 10, 10, 12, 12 );\n PaintHistoryInScreen( painter, wnd, mOpponentDeckRect.topRight() + QPoint( 20, 0 ) );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n move( x, y );\n setFixedSize( w, h );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n update();\n}\n\nvoid Overlay::Update() {\n if( Settings::Instance()->OverlayEnabled() ) {\n show();\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB[ cardId ][ \"type\" ] == \"hero\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB[ cardId ][ \"mana\" ];\n entry[ \"name\" ] = mCardDB[ cardId ][ \"name\" ];\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\nMake count more visible#include \"Overlay.h\"\n#include \"ui_Overlay.h\"\n\n#include \"..\/Hearthstone.h\"\n#include \"..\/Settings.h\"\n\n#ifdef Q_OS_MAC\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100\n\nclass OverlayHistoryWindow {\nprivate:\n QString mTitle;\n OverlayHistoryList mHistory;\n\n QFont mRowFont;\n QFont mTitleFont;\n\n int mWidth;\n\n int mPadding;\n int mRowSpacing;\n\n\n int TitleHeight() const {\n QFontMetrics titleMetrics( mTitleFont );\n return titleMetrics.ascent() - titleMetrics.descent();\n }\n\n int Padding() const {\n return mPadding;\n }\n\n int RowSpacing() const {\n return mRowSpacing;\n }\n\n int RowHeight() const {\n QFontMetrics rowMetrics( mRowFont );\n return rowMetrics.ascent() - rowMetrics.descent();\n }\n\n int RowWidth() const {\n return Width() - Padding() * 2;\n }\n\n void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const {\n \/\/ Draw mana\n QPen origPen = painter.pen();\n QPen pen( QColor( 0, 52, 113 ) );\n pen.setCosmetic( true );\n pen.setWidth( 1 );\n painter.setPen( pen );\n\n QBrush brush( QColor( 40, 119, 238 ) );\n painter.setBrush( brush );\n\n QTransform transform;\n painter.translate( x + width * 0.5, y + height * 0.5 );\n painter.scale( width * 0.8, height * 0.8 );\n\n static const QPointF points[5] = {\n QPointF( 0.0, -1.0 ),\n QPointF( 1.0, -0.2 ),\n QPointF( 0.6, 1.0 ),\n QPointF( -0.6, 1.0 ),\n QPointF( -1.0, -0.2 ),\n };\n painter.drawConvexPolygon( points, 5 );\n painter.resetTransform();\n painter.setPen( origPen );\n\n painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) );\n }\n\n void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const {\n painter.save();\n painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name );\n\n if( count > 1 ) {\n int nameWidth = QFontMetrics( painter.font() ).width( name + \" \" );\n QString countString = QString( \"x%1\" ).arg( count );\n QFont font = painter.font();\n font.setBold( true );\n painter.setFont( font );\n painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString );\n }\n painter.restore();\n }\n\npublic:\n OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, int titleFontSize, int rowFontSize )\n : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing )\n {\n mRowFont.setPixelSize( titleFontSize );\n mTitleFont.setPixelSize( rowFontSize );\n mTitleFont.setUnderline( true );\n mTitleFont.setBold( true );\n }\n\n int Width() const {\n return mWidth;\n }\n\n int Height() const {\n return ( mHistory.count() - 1 ) * RowSpacing() + \/\/ Spacing between items\n mHistory.count() * RowHeight() + \/\/ Height per item\n TitleHeight() + RowSpacing() + \/\/ Title\n Padding() * 2; \/\/ Overall padding\n }\n\n void Paint( QPainter& painter, int x, int y ) const {\n painter.save();\n\n QRect rect( x, y, Width(), Height() );\n painter.setClipRect( rect );\n\n \/\/ BG\n QPen pen = QPen( QColor( 160, 160, 160 ) );\n pen.setWidth( 3 );\n painter.setPen( pen );\n painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) );\n painter.drawRoundedRect( rect, 10, 10 );\n\n \/\/ Title\n y += Padding();\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mTitleFont );\n painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle );\n y += TitleHeight() + RowSpacing();\n\n \/\/ Lines\n painter.setPen( QPen( Qt::white) );\n painter.setFont( mRowFont );\n for( const QVariantMap& it : mHistory ) {\n int mx = x + Padding();\n DrawMana( painter, mx, y, RowHeight(), RowHeight(), it[\"mana\"].toInt() );\n int cx = mx + RowHeight() + 5;\n DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it[\"name\"].toString(), it[\"count\"].toInt() );\n y += RowHeight();\n y += RowSpacing();\n }\n\n painter.restore();\n }\n\n};\n\n\nOverlay::Overlay( QWidget *parent )\n : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN )\n{\n mUI->setupUi( this );\n setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::Window );\n setAttribute( Qt::WA_TranslucentBackground );\n\n connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged );\n connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted );\n connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped );\n\n connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover );\n\n connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged );\n\n LoadCards();\n\n hide();\n\n#ifdef Q_OS_MAC\n WId windowObject = this->winId();\n objc_object* nsviewObject = reinterpret_cast(windowObject);\n objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName(\"window\") );\n int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0;\n objc_msgSend( nsWindowObject, sel_registerName(\"setCollectionBehavior:\"), NSWindowCollectionBehaviorCanJoinAllSpaces );\n#endif\n}\n\nOverlay::~Overlay() {\n delete mUI;\n}\n\nvoid Overlay::CheckForHover() {\n QPoint mouseLoc = mapFromGlobal( QCursor::pos() );\n\n Player showPlayerHistory = PLAYER_UNKNOWN;\n\n if( mPlayerDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_SELF;\n } else if( mOpponentDeckRect.contains( mouseLoc ) ) {\n showPlayerHistory = PLAYER_OPPONENT;\n }\n\n if( mShowPlayerHistory != showPlayerHistory ) {\n mShowPlayerHistory = showPlayerHistory;\n update();\n }\n}\n\nvoid Overlay::LoadCards() {\n QFile file( \":\/data\/cards.json\" );\n bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );\n assert( opened );\n\n QByteArray jsonData = file.readAll();\n QJsonParseError error;\n QJsonArray jsonCards = QJsonDocument::fromJson( jsonData, &error ).array();\n assert( error.error == QJsonParseError::NoError );\n\n mCardDB.clear();\n\n for( QJsonValueRef jsonCardRef : jsonCards ) {\n QJsonObject jsonCard = jsonCardRef.toObject();\n mCardDB[ jsonCard[\"id\"].toString() ] = jsonCard.toVariantMap();\n }\n}\n\nvoid PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) {\n int padding = 10;\n\n QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() );\n rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); \/\/ fit to window\n wnd.Paint( painter, rect.x(), rect.y() );\n}\n\nvoid Overlay::paintEvent( QPaintEvent* ) {\n QPainter painter( this );\n painter.setRenderHint( QPainter::Antialiasing );\n\n int overlayWidth = 200;\n\n if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) {\n OverlayHistoryWindow wnd( \"Cards drawn\", mPlayerHistory, overlayWidth, 10, 10, 12, 12 );\n PaintHistoryInScreen( painter, wnd, mPlayerDeckRect.topRight() + QPoint( 20, 0 ) );\n } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) {\n OverlayHistoryWindow wnd( \"Cards played by opponent\", mOpponentHistory, overlayWidth, 10, 10, 12, 12 );\n PaintHistoryInScreen( painter, wnd, mOpponentDeckRect.topRight() + QPoint( 20, 0 ) );\n }\n}\n\nvoid Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) {\n move( x, y );\n setFixedSize( w, h );\n\n int minWidth = h * 4 \/ 3;\n mPlayerDeckRect = QRect( w \/ 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 );\n mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h );\n\n update();\n}\n\nvoid Overlay::Update() {\n if( Settings::Instance()->OverlayEnabled() ) {\n show();\n } else {\n hide();\n }\n\n update();\n}\n\nvoid Overlay::HandleGameStarted() {\n mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS );\n Update();\n}\n\nvoid Overlay::HandleGameStopped() {\n mCheckForHoverTimer.stop();\n Update();\n}\n\nvoid Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) {\n QMap< QString, QVariantMap > entries;\n\n for( const CardHistoryItem& it : list ) {\n const QString& cardId = it.cardId;\n\n if( cardId.isEmpty() ) {\n continue;\n }\n\n if( !mCardDB.contains( cardId ) ) {\n DBG( \"Card %s not found\", qt2cstr( cardId ) );\n continue;\n }\n\n if( mCardDB[ cardId ][ \"type\" ] == \"hero\" ) {\n continue;\n }\n\n if( it.player != player ) {\n continue;\n }\n\n QVariantMap& entry = entries[ cardId ];\n entry[ \"count\" ] = entry.value( \"count\", 0 ).toInt() + 1;\n entry[ \"mana\" ] = mCardDB[ cardId ][ \"mana\" ];\n entry[ \"name\" ] = mCardDB[ cardId ][ \"name\" ];\n }\n\n OverlayHistoryList* ref;\n if( player == PLAYER_SELF ) {\n ref = &mPlayerHistory;\n } else {\n ref = &mOpponentHistory;\n }\n\n *ref = entries.values();\n\n qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) {\n if( a[\"mana\"].toInt() == b[\"mana\"].toInt() ) {\n return a[\"name\"].toString() < b[\"name\"].toString();\n } else {\n return a[\"mana\"].toInt() < b[\"mana\"].toInt();\n }\n });\n}\n\nvoid Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) {\n UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn );\n UpdateHistoryFor( PLAYER_SELF, cardsDrawn );\n Update();\n}\n\nvoid Overlay::HandleOverlaySettingChanged( bool enabled ) {\n UNUSED_ARG( enabled );\n\n Update();\n}\n<|endoftext|>"} {"text":"\/* -------------------------------------------------------------------------- *\/\n\/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); you may *\/\n\/* not use this file except in compliance with the License. You may obtain *\/\n\/* a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *\/\n\/* See the License for the specific language governing permissions and *\/\n\/* limitations under the License. *\/\n\/* -------------------------------------------------------------------------- *\/\n\n#include \"LibVirtDriver.h\"\n\n#include \"Nebula.h\"\n#include \n#include \n#include \n\nint LibVirtDriver::deployment_description_vmware(\n const VirtualMachine * vm,\n const string& file_name) const\n{\n ofstream file;\n\n int num;\n vector attrs;\n\n string vcpu;\n string memory;\n\n int memory_in_kb = 0;\n\n string arch = \"\";\n\n const VectorAttribute * disk;\n const VectorAttribute * context;\n\n string type = \"\";\n string target = \"\";\n string bus = \"\";\n string ro = \"\";\n string source = \"\";\n string datastore = \"\";\n string driver = \"\";\n string default_driver = \"\";\n bool readonly;\n\n const VectorAttribute * nic;\n\n string mac = \"\";\n string bridge = \"\";\n string script = \"\";\n string model = \"\";\n\n const VectorAttribute * raw;\n string data;\n\n \/\/ ------------------------------------------------------------------------\n\n file.open(file_name.c_str(), ios::out);\n\n if (file.fail() == true)\n {\n goto error_vmware_file;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Starting XML document\n \/\/ ------------------------------------------------------------------------\n\n file << \"\" << endl;\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Domain name\n \/\/ ------------------------------------------------------------------------\n\n file << \"\\tone-\" << vm->get_oid() << \"<\/name>\" << endl;\n\n \/\/ ------------------------------------------------------------------------\n \/\/ CPU\n \/\/ ------------------------------------------------------------------------\n\n vm->get_template_attribute(\"VCPU\", vcpu);\n\n if(vcpu.empty())\n {\n get_default(\"VCPU\", vcpu);\n }\n\n if (!vcpu.empty())\n {\n file << \"\\t\" << vcpu << \"<\/vcpu>\" << endl;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Memory\n \/\/ ------------------------------------------------------------------------\n\n vm->get_template_attribute(\"MEMORY\",memory);\n\n if (memory.empty())\n {\n get_default(\"MEMORY\",memory);\n }\n\n if (!memory.empty())\n {\n memory_in_kb = atoi(memory.c_str()) * 1024;\n\n file << \"\\t\" << memory_in_kb << \"<\/memory>\" << endl;\n }\n else\n {\n goto error_vmware_memory;\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ OS and boot options\n \/\/ ------------------------------------------------------------------------\n\n num = vm->get_template_attribute(\"OS\",attrs);\n\n \/\/ Get values & defaults\n if ( num > 0 )\n {\n const VectorAttribute * os;\n\n os = dynamic_cast(attrs[0]);\n\n if( os != 0 )\n {\n arch = os->vector_value(\"ARCH\");\n }\n }\n\n if ( arch.empty() )\n {\n get_default(\"OS\",\"ARCH\",arch);\n\n if (arch.empty())\n {\n goto error_vmware_arch;\n }\n }\n\n \/\/ Start writing to the file with the info we got\n\n file << \"\\t\" << endl;\n\n file << \"\\t\\thvm<\/type>\" << endl;\n\n file << \"\\t<\/os>\" << endl;\n\n attrs.clear();\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Disks\n \/\/ ------------------------------------------------------------------------\n\n file << \"\\t\" << endl;\n \n get_default(\"DISK\",\"DRIVER\",default_driver);\n\n num = vm->get_template_attribute(\"DISK\",attrs);\n\n if (num!=0)\n {\n get_default(\"DATASTORE\", datastore);\n }\n\n for (int i=0; i < num ;i++)\n {\n disk = dynamic_cast(attrs[i]);\n\n if ( disk == 0 )\n {\n continue;\n }\n\n type = disk->vector_value(\"TYPE\");\n target = disk->vector_value(\"TARGET\");\n ro = disk->vector_value(\"READONLY\");\n bus = disk->vector_value(\"BUS\");\n source = disk->vector_value(\"SOURCE\");\n driver = disk->vector_value(\"DRIVER\");\n\n if (target.empty())\n {\n goto error_vmware_disk;\n }\n\n readonly = false;\n\n if ( !ro.empty() )\n {\n transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);\n\n if ( ro == \"YES\" )\n {\n readonly = true;\n }\n }\n\n if (type.empty() == false)\n {\n transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);\n }\n\n if ( type == \"BLOCK\" )\n {\n file << \"\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n }\n else if ( type == \"CDROM\" )\n {\n file << \"\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n }\n else\n {\n file << \"\\t\\t\" << endl\n << \"\\t\\t\\t\" << endl;\n }\n\n file << \"\\t\\t\\t\" << endl;\n }\n else\n {\n file << \"\/>\" << endl;\n }\n \n file << \"\\t\\t\\t\" << endl;\n }\n else\n {\n if (!default_driver.empty())\n {\n file << default_driver << \"'\/>\" << endl; \n }\n }\n\n if (readonly)\n {\n file << \"\\t\\t\\t\" << endl;\n }\n\n file << \"\\t\\t<\/disk>\" << endl;\n }\n\n attrs.clear();\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Context Device\n \/\/ ------------------------------------------------------------------------\n\n if ( vm->get_template_attribute(\"CONTEXT\",attrs) == 1 )\n {\n context = dynamic_cast(attrs[0]);\n target = context->vector_value(\"TARGET\");\n\n if ( !target.empty() )\n {\n file << \"\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n file << \"\\t\\t<\/disk>\" << endl;\n }\n else\n {\n vm->log(\"VMM\", Log::WARNING, \"Could not find target device to\"\n \" attach context, will continue without it.\");\n }\n }\n\n attrs.clear();\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Network interfaces\n \/\/ ------------------------------------------------------------------------\n\n num = vm->get_template_attribute(\"NIC\",attrs);\n\n for(int i=0; i(attrs[i]);\n\n if ( nic == 0 )\n {\n continue;\n }\n\n bridge = nic->vector_value(\"BRIDGE\");\n mac = nic->vector_value(\"MAC\");\n target = nic->vector_value(\"TARGET\");\n script = nic->vector_value(\"SCRIPT\");\n model = nic->vector_value(\"MODEL\");\n\n if ( bridge.empty() )\n {\n file << \"\\t\\t\" << endl;\n }\n else\n {\n file << \"\\t\\t\" << endl;\n file << \"\\t\\t\\t\" << endl;\n }\n\n if( !mac.empty() )\n {\n file << \"\\t\\t\\t\" << endl;\n }\n\n if( !target.empty() )\n {\n file << \"\\t\\t\\t\" << endl;\n }\n\n if( !script.empty() )\n {\n file << \"\\t\\t\\t