{"text":"#ifndef STDC11_HH\n#define STDC11_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* **\n * This file is juste a set of convenient standard methods from std11 such\n * as smart pointer and other stuff.\n *\/\n\n#define sign_form(T) typename std::make_signed::type\n#define sign_form_(T) std::make_signed::type\n\nnamespace std\n{\n\n template< typename T >\n inline T convert(const std::string& str)\n {\n std::istringstream iss(str);\n T obj;\n\n iss >> std::ws >> obj >> std::ws;\n\n if(!iss.eof())\n throw \"dammit!\";\n\n return obj; \n }\n const double PI = 3.14159265;\n\n template\n bool is_signed_cast_safe(T a)\n {\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n static_assert(!std::numeric_limits::is_signed, \"type must be unsigned\");\n\n typedef typename std::make_signed::type signed_T;\n typedef typename std::make_unsigned::type unsigned_T;\n\n return a < (unsigned_T) std::numeric_limits::max() ;\n \/\/&& a < (unsigned)std::numeric_limits::type>::max();\n }\n\n template\n bool is_cast_lossless(T a)\n {\n if(std::numeric_limits::digits >= std::numeric_limits::digits)\n return true;\n\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n\n return a <= static_cast(std::numeric_limits::max()) && \n a >= static_cast(std::numeric_limits::min());\n }\n\n template \n struct IF;\n template \n struct IF\n {\n typedef T2 res;\n };\n template \n struct IF\n {\n typedef T1 res;\n };\n\n template \n std::string to_string (T num)\n {\n std::ostringstream ss;\n ss << std::setprecision(3) << num;\n return ss.str();\n }\n\n template\n T round(T v)\n {\n return ::round(v);\n }\n\n template\n void tokenize(const std::string &str,\n ContainerT &tokens,\n const std::string &delimiters = \" \",\n bool trimEmpty = false)\n {\n std::string::size_type pos, lastPos = 0;\n while(true)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n if(lastPos != str.length())\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(str.length()-lastPos) ));\n break;\n }\n else\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(pos-lastPos) ));\n lastPos = pos + 1;\n }\n }\n\n}\n\n#endif\n\nAdd approximation equality#ifndef STDC11_HH\n#define STDC11_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* **\n * This file is juste a set of convenient standard methods from std11 such\n * as smart pointer and other stuff.\n *\/\n\n#define sign_form(T) typename std::make_signed::type\n#define sign_form_(T) std::make_signed::type\n\nnamespace std\n{\n template\n bool approx_equal(T a, T b, T epsilon=std::numeric_limits::epsilon())\n {\n if(std::numeric_limits::is_integer)\n if(exclude)\n return std::abs(a-b) < epsilon;\n else\n return std::abs(a-b) <= epsilon;\n else\n if(exclude)\n return std::fabs(a-b) < epsilon;\n else\n return std::fabs(a-b) <= epsilon;\n }\n\n template< typename T >\n inline T convert(const std::string& str)\n {\n std::istringstream iss(str);\n T obj;\n\n iss >> std::ws >> obj >> std::ws;\n\n if(!iss.eof())\n throw \"dammit!\";\n\n return obj; \n }\n const double PI = 3.14159265;\n\n template\n bool is_signed_cast_safe(T a)\n {\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n static_assert(!std::numeric_limits::is_signed, \"type must be unsigned\");\n\n typedef typename std::make_signed::type signed_T;\n typedef typename std::make_unsigned::type unsigned_T;\n\n return a < (unsigned_T) std::numeric_limits::max() ;\n \/\/&& a < (unsigned)std::numeric_limits::type>::max();\n }\n\n template\n bool is_cast_lossless(T a)\n {\n if(std::numeric_limits::digits >= std::numeric_limits::digits)\n return true;\n\n static_assert(std::numeric_limits::is_modulo, \"type must be 2 complement\");\n\n return a <= static_cast(std::numeric_limits::max()) && \n a >= static_cast(std::numeric_limits::min());\n }\n\n template \n struct IF;\n template \n struct IF\n {\n typedef T2 res;\n };\n template \n struct IF\n {\n typedef T1 res;\n };\n\n template \n std::string to_string (T num)\n {\n std::ostringstream ss;\n ss << std::setprecision(3) << num;\n return ss.str();\n }\n\n template\n T round(T v)\n {\n return ::round(v);\n }\n\n template\n void tokenize(const std::string &str,\n ContainerT &tokens,\n const std::string &delimiters = \" \",\n bool trimEmpty = false)\n {\n std::string::size_type pos, lastPos = 0;\n while(true)\n {\n pos = str.find_first_of(delimiters, lastPos);\n if(pos == std::string::npos)\n {\n if(lastPos != str.length())\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(str.length()-lastPos) ));\n break;\n }\n else\n if(pos != lastPos || !trimEmpty)\n tokens.push_back(std::string(str.data()+lastPos,\n (sizeof(T))*(pos-lastPos) ));\n lastPos = pos + 1;\n }\n }\n\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass transforms loops that contain branches on loop-invariant conditions\n\/\/ to have multiple loops. For example, it turns the left into the right code:\n\/\/\n\/\/ for (...) if (lic)\n\/\/ A for (...)\n\/\/ if (lic) A; B; C\n\/\/ B else\n\/\/ C for (...)\n\/\/ A; C\n\/\/\n\/\/ This can increase the size of the code exponentially (doubling it every time\n\/\/ a loop is unswitched) so we only unswitch if the resultant code will be\n\/\/ smaller than a threshold.\n\/\/\n\/\/ This pass expects LICM to be run before it to hoist invariant conditions out\n\/\/ of the loop, to make the unswitching opportunity obvious.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unswitch\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\nnamespace {\n Statistic<> NumUnswitched(\"loop-unswitch\", \"Number of loops unswitched\");\n\n class LoopUnswitch : public FunctionPass {\n LoopInfo *LI; \/\/ Loop information\n public:\n virtual bool runOnFunction(Function &F);\n bool visitLoop(Loop *L);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG...\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequiredID(LoopSimplifyID);\n AU.addRequired();\n AU.addPreserved();\n }\n\n private:\n void VersionLoop(Value *LIC, Loop *L);\n BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop);\n void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);\n };\n RegisterOpt X(\"loop-unswitch\", \"Unswitch loops\");\n}\n\nFunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }\n\nbool LoopUnswitch::runOnFunction(Function &F) {\n bool Changed = false;\n LI = &getAnalysis();\n\n \/\/ Transform all the top-level loops. Copy the loop list so that the child\n \/\/ can update the loop tree if it needs to delete the loop.\n std::vector SubLoops(LI->begin(), LI->end());\n for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)\n Changed |= visitLoop(SubLoops[i]);\n\n return Changed;\n}\n\n\n\/\/\/ InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of\n\/\/\/ the specified loop, insert a PHI node in the appropriate exit block to merge\n\/\/\/ the values in the two different loop versions.\n\/\/\/\n\/\/\/ Most values are not used outside of the loop they are defined in, so be\n\/\/\/ efficient for this case.\n\/\/\/\nstatic bool LoopValuesUsedOutsideLoop(Loop *L) {\n \/\/ We will be doing lots of \"loop contains block\" queries. Loop::contains is\n \/\/ linear time, use a set to speed this up.\n std::set LoopBlocks;\n\n for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();\n BB != E; ++BB)\n LoopBlocks.insert(*BB);\n \n for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();\n BB != E; ++BB) {\n for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;\n ++UI) {\n BasicBlock *UserBB = cast(*UI)->getParent();\n if (!LoopBlocks.count(UserBB))\n return true;\n }\n }\n return false;\n}\n\nbool LoopUnswitch::visitLoop(Loop *L) {\n bool Changed = false;\n\n \/\/ Recurse through all subloops before we process this loop. Copy the loop\n \/\/ list so that the child can update the loop tree if it needs to delete the\n \/\/ loop.\n std::vector SubLoops(L->begin(), L->end());\n for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)\n Changed |= visitLoop(SubLoops[i]);\n\n \/\/ Loop over all of the basic blocks in the loop. If we find an interior\n \/\/ block that is branching on a loop-invariant condition, we can unswitch this\n \/\/ loop.\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I) {\n TerminatorInst *TI = (*I)->getTerminator();\n if (SwitchInst *SI = dyn_cast(TI)) {\n if (!isa(SI) && L->isLoopInvariant(SI->getCondition()))\n DEBUG(std::cerr << \"TODO: Implement unswitching 'switch' loop %\"\n << L->getHeader()->getName() << \", cost = \"\n << L->getBlocks().size() << \"\\n\" << **I);\n continue;\n }\n \n BranchInst *BI = dyn_cast(TI);\n if (!BI) continue;\n \n \/\/ If this isn't branching on an invariant condition, we can't unswitch it.\n if (!BI->isConditional() || isa(BI->getCondition()) ||\n !L->isLoopInvariant(BI->getCondition()))\n continue;\n \n \/\/ Check to see if it would be profitable to unswitch this loop.\n if (L->getBlocks().size() > 10) {\n \/\/ FIXME: this should estimate growth by the amount of code shared by the\n \/\/ resultant unswitched loops. This should have no code growth:\n \/\/ for () { if (iv) {...} }\n \/\/ as one copy of the loop will be empty.\n \/\/\n DEBUG(std::cerr << \"NOT unswitching loop %\"\n << L->getHeader()->getName() << \", cost too high: \"\n << L->getBlocks().size() << \"\\n\");\n continue;\n }\n \n \/\/ If this loop has live-out values, we can't unswitch it. We need something\n \/\/ like loop-closed SSA form in order to know how to insert PHI nodes for\n \/\/ these values.\n if (LoopValuesUsedOutsideLoop(L)) {\n DEBUG(std::cerr << \"NOT unswitching loop %\"\n << L->getHeader()->getName()\n << \", a loop value is used outside loop!\\n\");\n continue;\n }\n \n \/\/std::cerr << \"BEFORE:\\n\"; LI->dump();\n VersionLoop(BI->getCondition(), L);\n \/\/std::cerr << \"AFTER:\\n\"; LI->dump();\n \n \/\/ FIXME: Why return here? What if we have:\n \/\/ \"for () { if (iv1) { if (iv2) { } } }\" ?\n return true;\n }\n\n return Changed;\n}\n\n\/\/\/ SplitBlock - Split the specified basic block into two pieces. If SplitAtTop\n\/\/\/ is false, this splits the block so the second half only has an unconditional\n\/\/\/ branch. If SplitAtTop is true, it makes it so the first half of the block\n\/\/\/ only has an unconditional branch in it.\n\/\/\/\n\/\/\/ This method updates the LoopInfo for this function to correctly reflect the\n\/\/\/ CFG changes made.\nBasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) {\n BasicBlock::iterator SplitPoint;\n if (!SplitAtTop)\n SplitPoint = BB->getTerminator();\n else {\n SplitPoint = BB->begin();\n while (isa(SplitPoint)) ++SplitPoint;\n }\n\n BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+\".tail\");\n \/\/ New now lives in whichever loop that BB used to.\n if (Loop *L = LI->getLoopFor(BB))\n L->addBasicBlockToLoop(New, *LI);\n return SplitAtTop ? BB : New;\n}\n\n\n\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/ current values into those specified by ValueMap.\n\/\/\nstatic inline void RemapInstruction(Instruction *I,\n std::map &ValueMap) {\n for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {\n Value *Op = I->getOperand(op);\n std::map::iterator It = ValueMap.find(Op);\n if (It != ValueMap.end()) Op = It->second;\n I->setOperand(op, Op);\n }\n}\n\n\/\/\/ CloneLoop - Recursively clone the specified loop and all of its children,\n\/\/\/ mapping the blocks with the specified map.\nstatic Loop *CloneLoop(Loop *L, Loop *PL, std::map &VM,\n LoopInfo *LI) {\n Loop *New = new Loop();\n\n if (PL)\n PL->addChildLoop(New);\n else\n LI->addTopLevelLoop(New);\n\n \/\/ Add all of the blocks in L to the new loop.\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I)\n if (LI->getLoopFor(*I) == L)\n New->addBasicBlockToLoop(cast(VM[*I]), *LI);\n\n \/\/ Add all of the subloops to the new loop.\n for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)\n CloneLoop(*I, New, VM, LI);\n\n return New;\n}\n\n\n\/\/\/ VersionLoop - We determined that the loop is profitable to unswitch and\n\/\/\/ contains a branch on a loop invariant condition. Split it into loop\n\/\/\/ versions and test the condition outside of either loop.\nvoid LoopUnswitch::VersionLoop(Value *LIC, Loop *L) {\n Function *F = L->getHeader()->getParent();\n\n DEBUG(std::cerr << \"loop-unswitch: Unswitching loop %\"\n << L->getHeader()->getName() << \" [\" << L->getBlocks().size()\n << \" blocks] in Function \" << F->getName()\n << \" on cond:\" << *LIC << \"\\n\");\n\n std::vector LoopBlocks;\n\n \/\/ First step, split the preheader and exit blocks, and add these blocks to\n \/\/ the LoopBlocks list.\n BasicBlock *OrigPreheader = L->getLoopPreheader();\n LoopBlocks.push_back(SplitBlock(OrigPreheader, false));\n\n \/\/ We want the loop to come after the preheader, but before the exit blocks.\n LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());\n\n std::vector ExitBlocks;\n L->getExitBlocks(ExitBlocks);\n std::sort(ExitBlocks.begin(), ExitBlocks.end());\n ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),\n ExitBlocks.end());\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true));\n\n \/\/ Next step, clone all of the basic blocks that make up the loop (including\n \/\/ the loop preheader and exit blocks), keeping track of the mapping between\n \/\/ the instructions and blocks.\n std::vector NewBlocks;\n NewBlocks.reserve(LoopBlocks.size());\n std::map ValueMap;\n for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {\n NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, \".us\", F));\n ValueMap[LoopBlocks[i]] = NewBlocks.back(); \/\/ Keep the BB mapping.\n }\n\n \/\/ Splice the newly inserted blocks into the function right before the\n \/\/ original preheader.\n F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),\n NewBlocks[0], F->end());\n\n \/\/ Now we create the new Loop object for the versioned loop.\n Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);\n if (Loop *Parent = L->getParentLoop()) {\n \/\/ Make sure to add the cloned preheader and exit blocks to the parent loop\n \/\/ as well.\n Parent->addBasicBlockToLoop(NewBlocks[0], *LI);\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n Parent->addBasicBlockToLoop(cast(ValueMap[ExitBlocks[i]]),\n *LI);\n }\n\n \/\/ Rewrite the code to refer to itself.\n for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)\n for (BasicBlock::iterator I = NewBlocks[i]->begin(),\n E = NewBlocks[i]->end(); I != E; ++I)\n RemapInstruction(I, ValueMap);\n \n \/\/ Rewrite the original preheader to select between versions of the loop.\n assert(isa(OrigPreheader->getTerminator()) &&\n cast(OrigPreheader->getTerminator())->isUnconditional() &&\n OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&\n \"Preheader splitting did not work correctly!\");\n \/\/ Remove the unconditional branch to LoopBlocks[0].\n OrigPreheader->getInstList().pop_back();\n\n \/\/ Insert a conditional branch on LIC to the two preheaders. The original\n \/\/ code is the true version and the new code is the false version.\n new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);\n\n \/\/ Now we rewrite the original code to know that the condition is true and the\n \/\/ new code to know that the condition is false.\n RewriteLoopBodyWithConditionConstant(L, LIC, true);\n RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);\n ++NumUnswitched;\n\n \/\/ Try to unswitch each of our new loops now!\n visitLoop(L);\n visitLoop(NewLoop);\n}\n\n\/\/ RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has\n\/\/ the value specified by Val in the specified loop. Rewrite any uses of LIC or\n\/\/ of properties correlated to it.\nvoid LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,\n bool Val) {\n \/\/ FIXME: Support correlated properties, like:\n \/\/ for (...)\n \/\/ if (li1 < li2)\n \/\/ ...\n \/\/ if (li1 > li2)\n \/\/ ...\n ConstantBool *BoolVal = ConstantBool::get(Val);\n\n std::vector Users(LIC->use_begin(), LIC->use_end());\n for (unsigned i = 0, e = Users.size(); i != e; ++i)\n if (Instruction *U = dyn_cast(Users[i]))\n if (L->contains(U->getParent()))\n U->replaceUsesOfWith(LIC, BoolVal);\n}\nMake the threshold a parameter\/\/===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass transforms loops that contain branches on loop-invariant conditions\n\/\/ to have multiple loops. For example, it turns the left into the right code:\n\/\/\n\/\/ for (...) if (lic)\n\/\/ A for (...)\n\/\/ if (lic) A; B; C\n\/\/ B else\n\/\/ C for (...)\n\/\/ A; C\n\/\/\n\/\/ This can increase the size of the code exponentially (doubling it every time\n\/\/ a loop is unswitched) so we only unswitch if the resultant code will be\n\/\/ smaller than a threshold.\n\/\/\n\/\/ This pass expects LICM to be run before it to hoist invariant conditions out\n\/\/ of the loop, to make the unswitching opportunity obvious.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"loop-unswitch\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Analysis\/LoopInfo.h\"\n#include \"llvm\/Transforms\/Utils\/Cloning.h\"\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\nnamespace {\n Statistic<> NumUnswitched(\"loop-unswitch\", \"Number of loops unswitched\");\n cl::opt\n Threshold(\"loop-unswitch-threshold\", cl::desc(\"Max loop size to unswitch\"),\n cl::init(10), cl::Hidden);\n \n class LoopUnswitch : public FunctionPass {\n LoopInfo *LI; \/\/ Loop information\n public:\n virtual bool runOnFunction(Function &F);\n bool visitLoop(Loop *L);\n\n \/\/\/ This transformation requires natural loop information & requires that\n \/\/\/ loop preheaders be inserted into the CFG...\n \/\/\/\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addRequiredID(LoopSimplifyID);\n AU.addRequired();\n AU.addPreserved();\n }\n\n private:\n void VersionLoop(Value *LIC, Loop *L);\n BasicBlock *SplitBlock(BasicBlock *BB, bool SplitAtTop);\n void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC, bool Val);\n };\n RegisterOpt X(\"loop-unswitch\", \"Unswitch loops\");\n}\n\nFunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }\n\nbool LoopUnswitch::runOnFunction(Function &F) {\n bool Changed = false;\n LI = &getAnalysis();\n\n \/\/ Transform all the top-level loops. Copy the loop list so that the child\n \/\/ can update the loop tree if it needs to delete the loop.\n std::vector SubLoops(LI->begin(), LI->end());\n for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)\n Changed |= visitLoop(SubLoops[i]);\n\n return Changed;\n}\n\n\n\/\/\/ InsertPHINodesForUsesOutsideLoop - If this instruction is used outside of\n\/\/\/ the specified loop, insert a PHI node in the appropriate exit block to merge\n\/\/\/ the values in the two different loop versions.\n\/\/\/\n\/\/\/ Most values are not used outside of the loop they are defined in, so be\n\/\/\/ efficient for this case.\n\/\/\/\nstatic bool LoopValuesUsedOutsideLoop(Loop *L) {\n \/\/ We will be doing lots of \"loop contains block\" queries. Loop::contains is\n \/\/ linear time, use a set to speed this up.\n std::set LoopBlocks;\n\n for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();\n BB != E; ++BB)\n LoopBlocks.insert(*BB);\n \n for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();\n BB != E; ++BB) {\n for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)\n for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;\n ++UI) {\n BasicBlock *UserBB = cast(*UI)->getParent();\n if (!LoopBlocks.count(UserBB))\n return true;\n }\n }\n return false;\n}\n\nbool LoopUnswitch::visitLoop(Loop *L) {\n bool Changed = false;\n\n \/\/ Recurse through all subloops before we process this loop. Copy the loop\n \/\/ list so that the child can update the loop tree if it needs to delete the\n \/\/ loop.\n std::vector SubLoops(L->begin(), L->end());\n for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)\n Changed |= visitLoop(SubLoops[i]);\n\n \/\/ Loop over all of the basic blocks in the loop. If we find an interior\n \/\/ block that is branching on a loop-invariant condition, we can unswitch this\n \/\/ loop.\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I) {\n TerminatorInst *TI = (*I)->getTerminator();\n if (SwitchInst *SI = dyn_cast(TI)) {\n if (!isa(SI) && L->isLoopInvariant(SI->getCondition()))\n DEBUG(std::cerr << \"TODO: Implement unswitching 'switch' loop %\"\n << L->getHeader()->getName() << \", cost = \"\n << L->getBlocks().size() << \"\\n\" << **I);\n continue;\n }\n \n BranchInst *BI = dyn_cast(TI);\n if (!BI) continue;\n \n \/\/ If this isn't branching on an invariant condition, we can't unswitch it.\n if (!BI->isConditional() || isa(BI->getCondition()) ||\n !L->isLoopInvariant(BI->getCondition()))\n continue;\n \n \/\/ Check to see if it would be profitable to unswitch this loop.\n if (L->getBlocks().size() > Threshold) {\n \/\/ FIXME: this should estimate growth by the amount of code shared by the\n \/\/ resultant unswitched loops. This should have no code growth:\n \/\/ for () { if (iv) {...} }\n \/\/ as one copy of the loop will be empty.\n \/\/\n DEBUG(std::cerr << \"NOT unswitching loop %\"\n << L->getHeader()->getName() << \", cost too high: \"\n << L->getBlocks().size() << \"\\n\");\n continue;\n }\n \n \/\/ If this loop has live-out values, we can't unswitch it. We need something\n \/\/ like loop-closed SSA form in order to know how to insert PHI nodes for\n \/\/ these values.\n if (LoopValuesUsedOutsideLoop(L)) {\n DEBUG(std::cerr << \"NOT unswitching loop %\"\n << L->getHeader()->getName()\n << \", a loop value is used outside loop!\\n\");\n continue;\n }\n \n \/\/std::cerr << \"BEFORE:\\n\"; LI->dump();\n VersionLoop(BI->getCondition(), L);\n \/\/std::cerr << \"AFTER:\\n\"; LI->dump();\n \n \/\/ FIXME: Why return here? What if we have:\n \/\/ \"for () { if (iv1) { if (iv2) { } } }\" ?\n return true;\n }\n\n return Changed;\n}\n\n\/\/\/ SplitBlock - Split the specified basic block into two pieces. If SplitAtTop\n\/\/\/ is false, this splits the block so the second half only has an unconditional\n\/\/\/ branch. If SplitAtTop is true, it makes it so the first half of the block\n\/\/\/ only has an unconditional branch in it.\n\/\/\/\n\/\/\/ This method updates the LoopInfo for this function to correctly reflect the\n\/\/\/ CFG changes made.\nBasicBlock *LoopUnswitch::SplitBlock(BasicBlock *BB, bool SplitAtTop) {\n BasicBlock::iterator SplitPoint;\n if (!SplitAtTop)\n SplitPoint = BB->getTerminator();\n else {\n SplitPoint = BB->begin();\n while (isa(SplitPoint)) ++SplitPoint;\n }\n\n BasicBlock *New = BB->splitBasicBlock(SplitPoint, BB->getName()+\".tail\");\n \/\/ New now lives in whichever loop that BB used to.\n if (Loop *L = LI->getLoopFor(BB))\n L->addBasicBlockToLoop(New, *LI);\n return SplitAtTop ? BB : New;\n}\n\n\n\/\/ RemapInstruction - Convert the instruction operands from referencing the\n\/\/ current values into those specified by ValueMap.\n\/\/\nstatic inline void RemapInstruction(Instruction *I,\n std::map &ValueMap) {\n for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {\n Value *Op = I->getOperand(op);\n std::map::iterator It = ValueMap.find(Op);\n if (It != ValueMap.end()) Op = It->second;\n I->setOperand(op, Op);\n }\n}\n\n\/\/\/ CloneLoop - Recursively clone the specified loop and all of its children,\n\/\/\/ mapping the blocks with the specified map.\nstatic Loop *CloneLoop(Loop *L, Loop *PL, std::map &VM,\n LoopInfo *LI) {\n Loop *New = new Loop();\n\n if (PL)\n PL->addChildLoop(New);\n else\n LI->addTopLevelLoop(New);\n\n \/\/ Add all of the blocks in L to the new loop.\n for (Loop::block_iterator I = L->block_begin(), E = L->block_end();\n I != E; ++I)\n if (LI->getLoopFor(*I) == L)\n New->addBasicBlockToLoop(cast(VM[*I]), *LI);\n\n \/\/ Add all of the subloops to the new loop.\n for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)\n CloneLoop(*I, New, VM, LI);\n\n return New;\n}\n\n\n\/\/\/ VersionLoop - We determined that the loop is profitable to unswitch and\n\/\/\/ contains a branch on a loop invariant condition. Split it into loop\n\/\/\/ versions and test the condition outside of either loop.\nvoid LoopUnswitch::VersionLoop(Value *LIC, Loop *L) {\n Function *F = L->getHeader()->getParent();\n\n DEBUG(std::cerr << \"loop-unswitch: Unswitching loop %\"\n << L->getHeader()->getName() << \" [\" << L->getBlocks().size()\n << \" blocks] in Function \" << F->getName()\n << \" on cond:\" << *LIC << \"\\n\");\n\n std::vector LoopBlocks;\n\n \/\/ First step, split the preheader and exit blocks, and add these blocks to\n \/\/ the LoopBlocks list.\n BasicBlock *OrigPreheader = L->getLoopPreheader();\n LoopBlocks.push_back(SplitBlock(OrigPreheader, false));\n\n \/\/ We want the loop to come after the preheader, but before the exit blocks.\n LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());\n\n std::vector ExitBlocks;\n L->getExitBlocks(ExitBlocks);\n std::sort(ExitBlocks.begin(), ExitBlocks.end());\n ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),\n ExitBlocks.end());\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n LoopBlocks.push_back(ExitBlocks[i] = SplitBlock(ExitBlocks[i], true));\n\n \/\/ Next step, clone all of the basic blocks that make up the loop (including\n \/\/ the loop preheader and exit blocks), keeping track of the mapping between\n \/\/ the instructions and blocks.\n std::vector NewBlocks;\n NewBlocks.reserve(LoopBlocks.size());\n std::map ValueMap;\n for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {\n NewBlocks.push_back(CloneBasicBlock(LoopBlocks[i], ValueMap, \".us\", F));\n ValueMap[LoopBlocks[i]] = NewBlocks.back(); \/\/ Keep the BB mapping.\n }\n\n \/\/ Splice the newly inserted blocks into the function right before the\n \/\/ original preheader.\n F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),\n NewBlocks[0], F->end());\n\n \/\/ Now we create the new Loop object for the versioned loop.\n Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);\n if (Loop *Parent = L->getParentLoop()) {\n \/\/ Make sure to add the cloned preheader and exit blocks to the parent loop\n \/\/ as well.\n Parent->addBasicBlockToLoop(NewBlocks[0], *LI);\n for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)\n Parent->addBasicBlockToLoop(cast(ValueMap[ExitBlocks[i]]),\n *LI);\n }\n\n \/\/ Rewrite the code to refer to itself.\n for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)\n for (BasicBlock::iterator I = NewBlocks[i]->begin(),\n E = NewBlocks[i]->end(); I != E; ++I)\n RemapInstruction(I, ValueMap);\n \n \/\/ Rewrite the original preheader to select between versions of the loop.\n assert(isa(OrigPreheader->getTerminator()) &&\n cast(OrigPreheader->getTerminator())->isUnconditional() &&\n OrigPreheader->getTerminator()->getSuccessor(0) == LoopBlocks[0] &&\n \"Preheader splitting did not work correctly!\");\n \/\/ Remove the unconditional branch to LoopBlocks[0].\n OrigPreheader->getInstList().pop_back();\n\n \/\/ Insert a conditional branch on LIC to the two preheaders. The original\n \/\/ code is the true version and the new code is the false version.\n new BranchInst(LoopBlocks[0], NewBlocks[0], LIC, OrigPreheader);\n\n \/\/ Now we rewrite the original code to know that the condition is true and the\n \/\/ new code to know that the condition is false.\n RewriteLoopBodyWithConditionConstant(L, LIC, true);\n RewriteLoopBodyWithConditionConstant(NewLoop, LIC, false);\n ++NumUnswitched;\n\n \/\/ Try to unswitch each of our new loops now!\n visitLoop(L);\n visitLoop(NewLoop);\n}\n\n\/\/ RewriteLoopBodyWithConditionConstant - We know that the boolean value LIC has\n\/\/ the value specified by Val in the specified loop. Rewrite any uses of LIC or\n\/\/ of properties correlated to it.\nvoid LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,\n bool Val) {\n \/\/ FIXME: Support correlated properties, like:\n \/\/ for (...)\n \/\/ if (li1 < li2)\n \/\/ ...\n \/\/ if (li1 > li2)\n \/\/ ...\n ConstantBool *BoolVal = ConstantBool::get(Val);\n\n std::vector Users(LIC->use_begin(), LIC->use_end());\n for (unsigned i = 0, e = Users.size(); i != e; ++i)\n if (Instruction *U = dyn_cast(Users[i]))\n if (L->contains(U->getParent()))\n U->replaceUsesOfWith(LIC, BoolVal);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTetra.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkTetra - a 3D cell that represents a tetrahedron\n\/\/ .SECTION Description\n\/\/ vtkTetra is a concrete implementation of vtkCell to represent a 3D\n\/\/ tetrahedron.\n\n#ifndef __vtkTetra_h\n#define __vtkTetra_h\n\n#include \"vtkCell.hh\"\n\nclass vtkTetra : public vtkCell\n{\npublic:\n vtkTetra() {};\n vtkTetra(const vtkTetra& t);\n char *GetClassName() {return \"vtkTetra\";};\n\n \/\/ cell methods\n vtkCell *MakeObject() {return new vtkTetra(*this);};\n int GetCellType() {return VTK_TETRA;};\n int GetCellDimension() {return 3;};\n int GetNumberOfEdges() {return 6;};\n int GetNumberOfFaces() {return 4;};\n vtkCell *GetEdge(int edgeId);\n vtkCell *GetFace(int faceId);\n\n int CellBoundary(int subId, float pcoords[3], vtkIdList& pts);\n void Contour(float value, vtkFloatScalars *cellScalars, \n vtkFloatPoints *points, vtkCellArray *verts, \n vtkCellArray *lines, vtkCellArray *polys, vtkFloatScalars *s);\n int EvaluatePosition(float x[3], float closestPoint[3],\n int& subId, float pcoords[3],\n float& dist2, float *weights);\n void EvaluateLocation(int& subId, float pcoords[3], float x[3],\n float *weights);\n int IntersectWithLine(float p1[3], float p2[3], float tol, float& t,\n float x[3], float pcoords[3], int& subId);\n int Triangulate(int index, vtkFloatPoints &pts);\n void Derivatives(int subId, float pcoords[3], float *values, \n int dim, float *derivs);\n\n \/\/ tetrahedron specific\n void TetraCenter(float p1[3], float p2[3], float p3[3], float p4[3], float center[3]);\n float Circumsphere(float p1[3], float p2[3], float p3[3], float p4[3], float center[3]);\n int BarycentricCoords(float x[3], float x1[3], float x2[3], float x3[3], \n float x4[3], float bcoords[4]);\n \n};\n\n#endif\n\n\n\nENH: Added derivative calculation.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkTetra.hh\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.\n\nThis software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.\nThe following terms apply to all files associated with the software unless\nexplicitly disclaimed in individual files. This copyright specifically does\nnot apply to the related textbook \"The Visualization Toolkit\" ISBN\n013199837-4 published by Prentice Hall which is covered by its own copyright.\n\nThe authors hereby grant permission to use, copy, and distribute this\nsoftware and its documentation for any purpose, provided that existing\ncopyright notices are retained in all copies and that this notice is included\nverbatim in any distributions. Additionally, the authors grant permission to\nmodify this software and its documentation for any purpose, provided that\nsuch modifications are not distributed without the explicit consent of the\nauthors and that existing copyright notices are retained in all copies. Some\nof the algorithms implemented by this software are patented, observe all\napplicable patent law.\n\nIN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR\nDIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\nOF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,\nEVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nTHE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,\nBUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN\n\"AS IS\" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE\nMAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\n=========================================================================*\/\n\/\/ .NAME vtkTetra - a 3D cell that represents a tetrahedron\n\/\/ .SECTION Description\n\/\/ vtkTetra is a concrete implementation of vtkCell to represent a 3D\n\/\/ tetrahedron.\n\n#ifndef __vtkTetra_h\n#define __vtkTetra_h\n\n#include \"vtkCell.hh\"\n\nclass vtkTetra : public vtkCell\n{\npublic:\n vtkTetra() {};\n vtkTetra(const vtkTetra& t);\n char *GetClassName() {return \"vtkTetra\";};\n\n \/\/ cell methods\n vtkCell *MakeObject() {return new vtkTetra(*this);};\n int GetCellType() {return VTK_TETRA;};\n int GetCellDimension() {return 3;};\n int GetNumberOfEdges() {return 6;};\n int GetNumberOfFaces() {return 4;};\n vtkCell *GetEdge(int edgeId);\n vtkCell *GetFace(int faceId);\n\n int CellBoundary(int subId, float pcoords[3], vtkIdList& pts);\n void Contour(float value, vtkFloatScalars *cellScalars, \n vtkFloatPoints *points, vtkCellArray *verts, \n vtkCellArray *lines, vtkCellArray *polys, vtkFloatScalars *s);\n int EvaluatePosition(float x[3], float closestPoint[3],\n int& subId, float pcoords[3],\n float& dist2, float *weights);\n void EvaluateLocation(int& subId, float pcoords[3], float x[3],\n float *weights);\n int IntersectWithLine(float p1[3], float p2[3], float tol, float& t,\n float x[3], float pcoords[3], int& subId);\n int Triangulate(int index, vtkFloatPoints &pts);\n void Derivatives(int subId, float pcoords[3], float *values, \n int dim, float *derivs);\n\n \/\/ tetrahedron specific\n void TetraCenter(float p1[3], float p2[3], float p3[3], float p4[3], float center[3]);\n float Circumsphere(float p1[3], float p2[3], float p3[3], float p4[3], float center[3]);\n int BarycentricCoords(float x[3], float x1[3], float x2[3], float x3[3], \n float x4[3], float bcoords[4]);\n \n void InterpolationFunctions(float pcoords[3], float weights[4]);\n void InterpolationDerivs(float derivs[12]);\n void JacobianInverse(double **inverse, float derivs[12]);\n\n};\n\n#endif\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hfi_module.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 11:58:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n#include \"hfi_module.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hfi_doc.hxx\"\n#include \"hfi_navibar.hxx\"\n#include \"hfi_tag.hxx\"\n#include \"hfi_typetext.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nextern const String\n C_sCePrefix_Module(\"module\");\n\nnamespace\n{\n\nconst String\n C_sList_NestedModules(\"Nested Modules\");\nconst String\n C_sList_NestedModules_Label(\"NestedModules\");\nconst String\n C_sList_Services(\"Services\");\nconst String\n C_sList_Singletons(\"Singletons\");\nconst String\n C_sList_Interfaces(\"Interfaces\");\nconst String\n C_sList_Structs(\"Structs\");\nconst String\n C_sList_Exceptions(\"Exceptions\");\nconst String\n C_sList_Enums(\"Enums\");\nconst String\n C_sList_Typedefs(\"Typedefs\");\nconst String\n C_sList_ConstGroups(\"Constant Groups\");\nconst String\n C_sList_ConstGroups_Label(\"ConstantGroups\");\n\n\nenum E_SubListIndices\n{ \/\/ In case of changes, also adapt make_Navibar() !!\n sli_NestedModules = 0,\n sli_Services = 1,\n sli_Singletons = 2,\n sli_Interfaces = 3,\n sli_Structs = 4,\n sli_Exceptions = 5,\n sli_Enums = 6,\n sli_Typedefs = 7,\n sli_ConstGroups = 8\n};\n\n} \/\/anonymous namespace\n\n\nHF_IdlModule::HF_IdlModule( Environment & io_rEnv,\n Xml::Element & o_rOut )\n : HtmlFactory_Idl(io_rEnv, &o_rOut)\n{\n}\n\nHF_IdlModule::~HF_IdlModule()\n{\n}\n\ntypedef ary::idl::ifc_module::attr ModuleAttr;\n\n\nvoid\nHF_IdlModule::Produce_byData( const client & i_ce ) const\n{\n Dyn\n pNaviSubRow( &make_Navibar(i_ce) );\n\n HF_TitleTable\n aTitle(CurOut());\n HF_LinkedNameChain\n aNameChain(aTitle.Add_Row());\n\n if ( Env().CurPosition().Depth() > 0 )\n {\n aNameChain.Produce_CompleteChain_forModule(Env().CurPosition(), nameChainLinker);\n\n StreamLock\n sl(200);\n aTitle.Produce_Title( sl()\n << C_sCePrefix_Module\n << \" \"\n << i_ce.LocalName()\n << c_str );\n }\n else\n {\n aTitle.Produce_Title( \"Global Module\" );\n }\n\n write_Docu(aTitle.Add_Row(), i_ce);\n CurOut() << new Html::HorizontalLine();\n\n\n \/\/ Write children lists:\n ce_ptr_list aNestedModules;\n ce_ptr_list aServices;\n ce_ptr_list aInterfaces;\n ce_ptr_list aStructs;\n ce_ptr_list aExceptions;\n ce_ptr_list aEnums;\n ce_ptr_list aTypedefs;\n ce_ptr_list aConstantGroups;\n ce_ptr_list aSingletons;\n\n ModuleAttr::Get_AllChildrenSeparated(\n aNestedModules,\n aServices,\n aInterfaces,\n aStructs,\n aExceptions,\n aEnums,\n aTypedefs,\n aConstantGroups,\n aSingletons,\n Env().Data().Ces(),\n i_ce );\n\n \/\/ Has this to be in the order of enum E_SubListIndices ???\n if (produce_ChildList(C_sList_NestedModules, C_sList_NestedModules_Label, aNestedModules ))\n pNaviSubRow->SwitchOn(sli_NestedModules);\n if (produce_ChildList(C_sList_Services, C_sList_Services, aServices))\n pNaviSubRow->SwitchOn(sli_Services);\n if (produce_ChildList(C_sList_Singletons, C_sList_Singletons, aSingletons))\n pNaviSubRow->SwitchOn(sli_Singletons);\n if (produce_ChildList(C_sList_Interfaces, C_sList_Interfaces, aInterfaces))\n pNaviSubRow->SwitchOn(sli_Interfaces);\n if (produce_ChildList(C_sList_Structs, C_sList_Structs, aStructs))\n pNaviSubRow->SwitchOn(sli_Structs);\n if (produce_ChildList(C_sList_Exceptions, C_sList_Exceptions, aExceptions))\n pNaviSubRow->SwitchOn(sli_Exceptions);\n if (produce_ChildList(C_sList_Enums, C_sList_Enums, aEnums))\n pNaviSubRow->SwitchOn(sli_Enums);\n if (produce_ChildList(C_sList_Typedefs, C_sList_Typedefs, aTypedefs))\n pNaviSubRow->SwitchOn(sli_Typedefs);\n if (produce_ChildList(C_sList_ConstGroups, C_sList_ConstGroups_Label, aConstantGroups))\n pNaviSubRow->SwitchOn(sli_ConstGroups);\n pNaviSubRow->Produce_Row();\n}\n\nDYN HF_NaviSubRow &\nHF_IdlModule::make_Navibar( const client & i_ce ) const\n{\n HF_IdlNavigationBar\n aNaviBar(Env(), CurOut());\n aNaviBar.Produce_ModuleMainRow(i_ce);\n\n DYN HF_NaviSubRow &\n ret = aNaviBar.Add_SubRow();\n\n \/\/ Has to be in the order of E_SubListIndices:\n ret.AddItem(C_sList_NestedModules, C_sList_NestedModules_Label, false);\n ret.AddItem(C_sList_Services, C_sList_Services, false);\n ret.AddItem(C_sList_Singletons, C_sList_Singletons, false);\n ret.AddItem(C_sList_Interfaces, C_sList_Interfaces, false);\n ret.AddItem(C_sList_Structs, C_sList_Structs, false);\n ret.AddItem(C_sList_Exceptions, C_sList_Exceptions, false);\n ret.AddItem(C_sList_Enums, C_sList_Enums, false);\n ret.AddItem(C_sList_Typedefs, C_sList_Typedefs, false);\n ret.AddItem(C_sList_ConstGroups, C_sList_ConstGroups_Label, false);\n\n CurOut() << new Html::HorizontalLine();\n return ret;\n}\n\nbool\nHF_IdlModule::produce_ChildList( const String & i_sName,\n const String & i_sLabel,\n const ce_ptr_list & i_list ) const\n{\n if ( i_list.size() == 0 )\n return false;\n\n HF_SubTitleTable\n aTable( CurOut(),\n i_sLabel,\n i_sName,\n 2 );\n\n ce_ptr_list::const_iterator\n itEnd = i_list.end();\n for ( ce_ptr_list::const_iterator it = i_list.begin();\n it != itEnd;\n ++it )\n {\n Xml::Element &\n rRow = aTable.Add_Row();\n produce_Link(rRow, *it);\n produce_LinkDoc(rRow, *it);\n } \/\/ end for\n\n return true;\n}\n\nvoid\nHF_IdlModule::produce_Link( Xml::Element & o_row,\n const client * i_ce ) const\n{\n csv_assert(i_ce != 0);\n Xml::Element &\n rCell = o_row\n >> *new Html::TableCell\n << new Html::ClassAttr(C_sCellStyle_SummaryLeft);\n\n if (i_ce->ClassId() != ary::idl::Module::class_id)\n {\n HF_IdlTypeText\n aText(Env(), rCell, true);\n aText.Produce_byData(i_ce->CeId());\n }\n else\n {\n StreamLock slBuf(100);\n rCell\n >> *new Html::Link( slBuf() << i_ce->LocalName()\n << \"\/module-ix.html\"\n << c_str )\n << i_ce->LocalName();\n }\n}\n\nvoid\nHF_IdlModule::produce_LinkDoc( Xml::Element & o_row,\n const client * i_ce ) const\n{\n csv_assert(i_ce != 0);\n\n \/\/ We need the cell in any case, because, the rendering may be hurt else.\n Xml::Element &\n rCell = o_row\n >> *new Html::TableCell\n << new Html::ClassAttr(C_sCellStyle_SummaryRight);\n\n const client &\n rCe = *i_ce;\n const ce_info *\n pShort = rCe.Docu();\n if ( pShort == 0 )\n return;\n\n\n if (pShort->IsDeprecated())\n {\n rCell << \"[ DEPRECATED ]\" << new Html::LineBreak;\n }\n if (pShort->IsOptional())\n {\n rCell << \"[ OPTIONAL ]\" << new Html::LineBreak;\n }\n\n HF_IdlDocuTextDisplay\n aShortDisplay(Env(), &rCell, *i_ce);\n pShort->Short().DisplayAt(aShortDisplay);\n}\nINTEGRATION: CWS pchfix02 (1.4.6); FILE MERGED 2006\/09\/01 17:15:34 kaib 1.4.6.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: hfi_module.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 16:47:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_autodoc.hxx\"\n\n\n#include \n#include \"hfi_module.hxx\"\n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"hfi_doc.hxx\"\n#include \"hfi_navibar.hxx\"\n#include \"hfi_tag.hxx\"\n#include \"hfi_typetext.hxx\"\n#include \"hi_linkhelper.hxx\"\n\n\nextern const String\n C_sCePrefix_Module(\"module\");\n\nnamespace\n{\n\nconst String\n C_sList_NestedModules(\"Nested Modules\");\nconst String\n C_sList_NestedModules_Label(\"NestedModules\");\nconst String\n C_sList_Services(\"Services\");\nconst String\n C_sList_Singletons(\"Singletons\");\nconst String\n C_sList_Interfaces(\"Interfaces\");\nconst String\n C_sList_Structs(\"Structs\");\nconst String\n C_sList_Exceptions(\"Exceptions\");\nconst String\n C_sList_Enums(\"Enums\");\nconst String\n C_sList_Typedefs(\"Typedefs\");\nconst String\n C_sList_ConstGroups(\"Constant Groups\");\nconst String\n C_sList_ConstGroups_Label(\"ConstantGroups\");\n\n\nenum E_SubListIndices\n{ \/\/ In case of changes, also adapt make_Navibar() !!\n sli_NestedModules = 0,\n sli_Services = 1,\n sli_Singletons = 2,\n sli_Interfaces = 3,\n sli_Structs = 4,\n sli_Exceptions = 5,\n sli_Enums = 6,\n sli_Typedefs = 7,\n sli_ConstGroups = 8\n};\n\n} \/\/anonymous namespace\n\n\nHF_IdlModule::HF_IdlModule( Environment & io_rEnv,\n Xml::Element & o_rOut )\n : HtmlFactory_Idl(io_rEnv, &o_rOut)\n{\n}\n\nHF_IdlModule::~HF_IdlModule()\n{\n}\n\ntypedef ary::idl::ifc_module::attr ModuleAttr;\n\n\nvoid\nHF_IdlModule::Produce_byData( const client & i_ce ) const\n{\n Dyn\n pNaviSubRow( &make_Navibar(i_ce) );\n\n HF_TitleTable\n aTitle(CurOut());\n HF_LinkedNameChain\n aNameChain(aTitle.Add_Row());\n\n if ( Env().CurPosition().Depth() > 0 )\n {\n aNameChain.Produce_CompleteChain_forModule(Env().CurPosition(), nameChainLinker);\n\n StreamLock\n sl(200);\n aTitle.Produce_Title( sl()\n << C_sCePrefix_Module\n << \" \"\n << i_ce.LocalName()\n << c_str );\n }\n else\n {\n aTitle.Produce_Title( \"Global Module\" );\n }\n\n write_Docu(aTitle.Add_Row(), i_ce);\n CurOut() << new Html::HorizontalLine();\n\n\n \/\/ Write children lists:\n ce_ptr_list aNestedModules;\n ce_ptr_list aServices;\n ce_ptr_list aInterfaces;\n ce_ptr_list aStructs;\n ce_ptr_list aExceptions;\n ce_ptr_list aEnums;\n ce_ptr_list aTypedefs;\n ce_ptr_list aConstantGroups;\n ce_ptr_list aSingletons;\n\n ModuleAttr::Get_AllChildrenSeparated(\n aNestedModules,\n aServices,\n aInterfaces,\n aStructs,\n aExceptions,\n aEnums,\n aTypedefs,\n aConstantGroups,\n aSingletons,\n Env().Data().Ces(),\n i_ce );\n\n \/\/ Has this to be in the order of enum E_SubListIndices ???\n if (produce_ChildList(C_sList_NestedModules, C_sList_NestedModules_Label, aNestedModules ))\n pNaviSubRow->SwitchOn(sli_NestedModules);\n if (produce_ChildList(C_sList_Services, C_sList_Services, aServices))\n pNaviSubRow->SwitchOn(sli_Services);\n if (produce_ChildList(C_sList_Singletons, C_sList_Singletons, aSingletons))\n pNaviSubRow->SwitchOn(sli_Singletons);\n if (produce_ChildList(C_sList_Interfaces, C_sList_Interfaces, aInterfaces))\n pNaviSubRow->SwitchOn(sli_Interfaces);\n if (produce_ChildList(C_sList_Structs, C_sList_Structs, aStructs))\n pNaviSubRow->SwitchOn(sli_Structs);\n if (produce_ChildList(C_sList_Exceptions, C_sList_Exceptions, aExceptions))\n pNaviSubRow->SwitchOn(sli_Exceptions);\n if (produce_ChildList(C_sList_Enums, C_sList_Enums, aEnums))\n pNaviSubRow->SwitchOn(sli_Enums);\n if (produce_ChildList(C_sList_Typedefs, C_sList_Typedefs, aTypedefs))\n pNaviSubRow->SwitchOn(sli_Typedefs);\n if (produce_ChildList(C_sList_ConstGroups, C_sList_ConstGroups_Label, aConstantGroups))\n pNaviSubRow->SwitchOn(sli_ConstGroups);\n pNaviSubRow->Produce_Row();\n}\n\nDYN HF_NaviSubRow &\nHF_IdlModule::make_Navibar( const client & i_ce ) const\n{\n HF_IdlNavigationBar\n aNaviBar(Env(), CurOut());\n aNaviBar.Produce_ModuleMainRow(i_ce);\n\n DYN HF_NaviSubRow &\n ret = aNaviBar.Add_SubRow();\n\n \/\/ Has to be in the order of E_SubListIndices:\n ret.AddItem(C_sList_NestedModules, C_sList_NestedModules_Label, false);\n ret.AddItem(C_sList_Services, C_sList_Services, false);\n ret.AddItem(C_sList_Singletons, C_sList_Singletons, false);\n ret.AddItem(C_sList_Interfaces, C_sList_Interfaces, false);\n ret.AddItem(C_sList_Structs, C_sList_Structs, false);\n ret.AddItem(C_sList_Exceptions, C_sList_Exceptions, false);\n ret.AddItem(C_sList_Enums, C_sList_Enums, false);\n ret.AddItem(C_sList_Typedefs, C_sList_Typedefs, false);\n ret.AddItem(C_sList_ConstGroups, C_sList_ConstGroups_Label, false);\n\n CurOut() << new Html::HorizontalLine();\n return ret;\n}\n\nbool\nHF_IdlModule::produce_ChildList( const String & i_sName,\n const String & i_sLabel,\n const ce_ptr_list & i_list ) const\n{\n if ( i_list.size() == 0 )\n return false;\n\n HF_SubTitleTable\n aTable( CurOut(),\n i_sLabel,\n i_sName,\n 2 );\n\n ce_ptr_list::const_iterator\n itEnd = i_list.end();\n for ( ce_ptr_list::const_iterator it = i_list.begin();\n it != itEnd;\n ++it )\n {\n Xml::Element &\n rRow = aTable.Add_Row();\n produce_Link(rRow, *it);\n produce_LinkDoc(rRow, *it);\n } \/\/ end for\n\n return true;\n}\n\nvoid\nHF_IdlModule::produce_Link( Xml::Element & o_row,\n const client * i_ce ) const\n{\n csv_assert(i_ce != 0);\n Xml::Element &\n rCell = o_row\n >> *new Html::TableCell\n << new Html::ClassAttr(C_sCellStyle_SummaryLeft);\n\n if (i_ce->ClassId() != ary::idl::Module::class_id)\n {\n HF_IdlTypeText\n aText(Env(), rCell, true);\n aText.Produce_byData(i_ce->CeId());\n }\n else\n {\n StreamLock slBuf(100);\n rCell\n >> *new Html::Link( slBuf() << i_ce->LocalName()\n << \"\/module-ix.html\"\n << c_str )\n << i_ce->LocalName();\n }\n}\n\nvoid\nHF_IdlModule::produce_LinkDoc( Xml::Element & o_row,\n const client * i_ce ) const\n{\n csv_assert(i_ce != 0);\n\n \/\/ We need the cell in any case, because, the rendering may be hurt else.\n Xml::Element &\n rCell = o_row\n >> *new Html::TableCell\n << new Html::ClassAttr(C_sCellStyle_SummaryRight);\n\n const client &\n rCe = *i_ce;\n const ce_info *\n pShort = rCe.Docu();\n if ( pShort == 0 )\n return;\n\n\n if (pShort->IsDeprecated())\n {\n rCell << \"[ DEPRECATED ]\" << new Html::LineBreak;\n }\n if (pShort->IsOptional())\n {\n rCell << \"[ OPTIONAL ]\" << new Html::LineBreak;\n }\n\n HF_IdlDocuTextDisplay\n aShortDisplay(Env(), &rCell, *i_ce);\n pShort->Short().DisplayAt(aShortDisplay);\n}\n<|endoftext|>"} {"text":"\/\/===- Main.cpp - Top-Level TableGen implementation -----------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ TableGen is a tool which can be used to build up a description of something,\n\/\/ then invoke one or more \"tablegen backends\" to emit information about the\n\/\/ description in some predefined format. In practice, this is used by the LLVM\n\/\/ code generators to automate generation of a code generator through a\n\/\/ high-level description of the target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/TableGen\/Main.h\"\n#include \"TGParser.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"),\n cl::init(\"-\"));\n\nstatic cl::opt\nDependFilename(\"d\",\n cl::desc(\"Dependency filename\"),\n cl::value_desc(\"filename\"),\n cl::init(\"\"));\n\nstatic cl::opt\nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::list\nIncludeDirs(\"I\", cl::desc(\"Directory of include files\"),\n cl::value_desc(\"directory\"), cl::Prefix);\n\nstatic cl::list\nMacroNames(\"D\", cl::desc(\"Name of the macro to be defined\"),\n cl::value_desc(\"macro name\"), cl::Prefix);\n\nstatic int reportError(const char *ProgName, Twine Msg) {\n errs() << ProgName << \": \" << Msg;\n errs().flush();\n return 1;\n}\n\n\/\/\/ Create a dependency file for `-d` option.\n\/\/\/\n\/\/\/ This functionality is really only for the benefit of the build system.\n\/\/\/ It is similar to GCC's `-M*` family of options.\nstatic int createDependencyFile(const TGParser &Parser, const char *argv0) {\n if (OutputFilename == \"-\")\n return reportError(argv0, \"the option -d must be used together with -o\\n\");\n\n std::error_code EC;\n ToolOutputFile DepOut(DependFilename, EC, sys::fs::OF_Text);\n if (EC)\n return reportError(argv0, \"error opening \" + DependFilename + \":\" +\n EC.message() + \"\\n\");\n DepOut.os() << OutputFilename << \":\";\n for (const auto &Dep : Parser.getDependencies()) {\n DepOut.os() << ' ' << Dep.first;\n }\n DepOut.os() << \"\\n\";\n DepOut.keep();\n return 0;\n}\n\nint llvm::TableGenMain(char *argv0, TableGenMainFn *MainFn) {\n RecordKeeper Records;\n\n \/\/ Parse the input file.\n ErrorOr> FileOrErr =\n MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (std::error_code EC = FileOrErr.getError())\n return reportError(argv0, \"Could not open input file '\" + InputFilename +\n \"': \" + EC.message() + \"\\n\");\n\n \/\/ Tell SrcMgr about this buffer, which is what TGParser will pick up.\n SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());\n\n \/\/ Record the location of the include directory so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(IncludeDirs);\n\n TGParser Parser(SrcMgr, MacroNames, Records);\n\n if (Parser.ParseFile())\n return 1;\n\n \/\/ Write output to memory.\n std::string OutString;\n raw_string_ostream Out(OutString);\n if (MainFn(Out, Records))\n return 1;\n\n \/\/ Always write the depfile, even if the main output hasn't changed.\n \/\/ If it's missing, Ninja considers the output dirty. If this was below\n \/\/ the early exit below and someone deleted the .inc.d file but not the .inc\n \/\/ file, tablegen would never write the depfile.\n if (!DependFilename.empty()) {\n if (int Ret = createDependencyFile(Parser, argv0))\n return Ret;\n }\n\n \/\/ Only updates the real output file if there are any differences.\n \/\/ This prevents recompilation of all the files depending on it if there\n \/\/ aren't any.\n if (auto ExistingOrErr = MemoryBuffer::getFile(OutputFilename))\n if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())\n return 0;\n\n std::error_code EC;\n ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_Text);\n if (EC)\n return reportError(argv0, \"error opening \" + OutputFilename + \":\" +\n EC.message() + \"\\n\");\n OutFile.os() << Out.str();\n\n if (ErrorsPrinted > 0)\n return reportError(argv0, Twine(ErrorsPrinted) + \" errors.\\n\");\n\n \/\/ Declare success.\n OutFile.keep();\n return 0;\n}\n[TableGen] Skip CRLF conversion when writing output\/\/===- Main.cpp - Top-Level TableGen implementation -----------------------===\/\/\n\/\/\n\/\/ Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.\n\/\/ See https:\/\/llvm.org\/LICENSE.txt for license information.\n\/\/ SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ TableGen is a tool which can be used to build up a description of something,\n\/\/ then invoke one or more \"tablegen backends\" to emit information about the\n\/\/ description in some predefined format. In practice, this is used by the LLVM\n\/\/ code generators to automate generation of a code generator through a\n\/\/ high-level description of the target.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/TableGen\/Main.h\"\n#include \"TGParser.h\"\n#include \"llvm\/ADT\/StringExtras.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/Support\/ToolOutputFile.h\"\n#include \"llvm\/TableGen\/Error.h\"\n#include \"llvm\/TableGen\/Record.h\"\n#include \n#include \n#include \nusing namespace llvm;\n\nstatic cl::opt\nOutputFilename(\"o\", cl::desc(\"Output filename\"), cl::value_desc(\"filename\"),\n cl::init(\"-\"));\n\nstatic cl::opt\nDependFilename(\"d\",\n cl::desc(\"Dependency filename\"),\n cl::value_desc(\"filename\"),\n cl::init(\"\"));\n\nstatic cl::opt\nInputFilename(cl::Positional, cl::desc(\"\"), cl::init(\"-\"));\n\nstatic cl::list\nIncludeDirs(\"I\", cl::desc(\"Directory of include files\"),\n cl::value_desc(\"directory\"), cl::Prefix);\n\nstatic cl::list\nMacroNames(\"D\", cl::desc(\"Name of the macro to be defined\"),\n cl::value_desc(\"macro name\"), cl::Prefix);\n\nstatic int reportError(const char *ProgName, Twine Msg) {\n errs() << ProgName << \": \" << Msg;\n errs().flush();\n return 1;\n}\n\n\/\/\/ Create a dependency file for `-d` option.\n\/\/\/\n\/\/\/ This functionality is really only for the benefit of the build system.\n\/\/\/ It is similar to GCC's `-M*` family of options.\nstatic int createDependencyFile(const TGParser &Parser, const char *argv0) {\n if (OutputFilename == \"-\")\n return reportError(argv0, \"the option -d must be used together with -o\\n\");\n\n std::error_code EC;\n ToolOutputFile DepOut(DependFilename, EC, sys::fs::OF_None);\n if (EC)\n return reportError(argv0, \"error opening \" + DependFilename + \":\" +\n EC.message() + \"\\n\");\n DepOut.os() << OutputFilename << \":\";\n for (const auto &Dep : Parser.getDependencies()) {\n DepOut.os() << ' ' << Dep.first;\n }\n DepOut.os() << \"\\n\";\n DepOut.keep();\n return 0;\n}\n\nint llvm::TableGenMain(char *argv0, TableGenMainFn *MainFn) {\n RecordKeeper Records;\n\n \/\/ Parse the input file.\n ErrorOr> FileOrErr =\n MemoryBuffer::getFileOrSTDIN(InputFilename);\n if (std::error_code EC = FileOrErr.getError())\n return reportError(argv0, \"Could not open input file '\" + InputFilename +\n \"': \" + EC.message() + \"\\n\");\n\n \/\/ Tell SrcMgr about this buffer, which is what TGParser will pick up.\n SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());\n\n \/\/ Record the location of the include directory so that the lexer can find\n \/\/ it later.\n SrcMgr.setIncludeDirs(IncludeDirs);\n\n TGParser Parser(SrcMgr, MacroNames, Records);\n\n if (Parser.ParseFile())\n return 1;\n\n \/\/ Write output to memory.\n std::string OutString;\n raw_string_ostream Out(OutString);\n if (MainFn(Out, Records))\n return 1;\n\n \/\/ Always write the depfile, even if the main output hasn't changed.\n \/\/ If it's missing, Ninja considers the output dirty. If this was below\n \/\/ the early exit below and someone deleted the .inc.d file but not the .inc\n \/\/ file, tablegen would never write the depfile.\n if (!DependFilename.empty()) {\n if (int Ret = createDependencyFile(Parser, argv0))\n return Ret;\n }\n\n \/\/ Only updates the real output file if there are any differences.\n \/\/ This prevents recompilation of all the files depending on it if there\n \/\/ aren't any.\n if (auto ExistingOrErr = MemoryBuffer::getFile(OutputFilename))\n if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())\n return 0;\n\n std::error_code EC;\n ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);\n if (EC)\n return reportError(argv0, \"error opening \" + OutputFilename + \":\" +\n EC.message() + \"\\n\");\n OutFile.os() << Out.str();\n\n if (ErrorsPrinted > 0)\n return reportError(argv0, Twine(ErrorsPrinted) + \" errors.\\n\");\n\n \/\/ Declare success.\n OutFile.keep();\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/native_mate_converters\/net_converter.h\"\n\n#include \n\n#include \"atom\/common\/node_includes.h\"\n#include \"native_mate\/dictionary.h\"\n#include \"net\/cert\/x509_certificate.h\"\n#include \"net\/url_request\/url_request.h\"\n\nnamespace mate {\n\n\/\/ static\nv8::Local Converter::ToV8(\n v8::Isolate* isolate, const net::URLRequest* val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"method\", val->method());\n dict.Set(\"url\", val->url().spec());\n dict.Set(\"referrer\", val->referrer());\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local Converter::ToV8(\n v8::Isolate* isolate, const net::AuthChallengeInfo* val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"isProxy\", val->is_proxy);\n dict.Set(\"scheme\", val->scheme);\n dict.Set(\"host\", val->challenger.host());\n dict.Set(\"port\", static_cast(val->challenger.port()));\n dict.Set(\"realm\", val->realm);\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local Converter>::ToV8(\n v8::Isolate* isolate, const scoped_refptr& val) {\n mate::Dictionary dict(isolate, v8::Object::New(isolate));\n std::string encoded_data;\n net::X509Certificate::GetPEMEncoded(\n val->os_cert_handle(), &encoded_data);\n auto buffer = node::Buffer::Copy(isolate,\n encoded_data.data(),\n encoded_data.size()).ToLocalChecked();\n dict.Set(\"data\", buffer);\n dict.Set(\"issuerName\", val->issuer().GetDisplayName());\n return dict.GetHandle();\n}\n\n} \/\/ namespace mate\nprotocol: provide upload data when available\/\/ Copyright (c) 2015 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"atom\/common\/native_mate_converters\/net_converter.h\"\n\n#include \n#include \n\n#include \"atom\/common\/node_includes.h\"\n#include \"native_mate\/dictionary.h\"\n#include \"net\/base\/upload_bytes_element_reader.h\"\n#include \"net\/base\/upload_data_stream.h\"\n#include \"net\/base\/upload_element_reader.h\"\n#include \"net\/base\/upload_file_element_reader.h\"\n#include \"net\/cert\/x509_certificate.h\"\n#include \"net\/url_request\/url_request.h\"\n\nnamespace mate {\n\n\/\/ static\nv8::Local Converter::ToV8(\n v8::Isolate* isolate, const net::URLRequest* val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"method\", val->method());\n dict.Set(\"url\", val->url().spec());\n dict.Set(\"referrer\", val->referrer());\n const net::UploadDataStream* upload_data = val->get_upload();\n if (upload_data) {\n const ScopedVector* readers =\n upload_data->GetElementReaders();\n std::vector upload_data_list;\n upload_data_list.reserve(readers->size());\n for (const auto& reader : *readers) {\n auto upload_data_dict = mate::Dictionary::CreateEmpty(isolate);\n if (reader->AsBytesReader()) {\n const net::UploadBytesElementReader* bytes_reader =\n reader->AsBytesReader();\n auto bytes =\n node::Buffer::Copy(isolate, bytes_reader->bytes(),\n bytes_reader->length()).ToLocalChecked();\n upload_data_dict.Set(\"bytes\", bytes);\n } else if (reader->AsFileReader()) {\n const net::UploadFileElementReader* file_reader =\n reader->AsFileReader();\n upload_data_dict.Set(\"file\", file_reader->path().AsUTF8Unsafe());\n }\n upload_data_list.push_back(upload_data_dict);\n }\n dict.Set(\"uploadData\", upload_data_list);\n }\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local Converter::ToV8(\n v8::Isolate* isolate, const net::AuthChallengeInfo* val) {\n mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);\n dict.Set(\"isProxy\", val->is_proxy);\n dict.Set(\"scheme\", val->scheme);\n dict.Set(\"host\", val->challenger.host());\n dict.Set(\"port\", static_cast(val->challenger.port()));\n dict.Set(\"realm\", val->realm);\n return mate::ConvertToV8(isolate, dict);\n}\n\n\/\/ static\nv8::Local Converter>::ToV8(\n v8::Isolate* isolate, const scoped_refptr& val) {\n mate::Dictionary dict(isolate, v8::Object::New(isolate));\n std::string encoded_data;\n net::X509Certificate::GetPEMEncoded(\n val->os_cert_handle(), &encoded_data);\n auto buffer = node::Buffer::Copy(isolate,\n encoded_data.data(),\n encoded_data.size()).ToLocalChecked();\n dict.Set(\"data\", buffer);\n dict.Set(\"issuerName\", val->issuer().GetDisplayName());\n return dict.GetHandle();\n}\n\n} \/\/ namespace mate\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mthemedaemonprotocol.h\"\n#include \n#include \n\nusing namespace M::MThemeDaemonProtocol;\n\nconst QString M::MThemeDaemonProtocol::ServerAddress = \"m.mthemedaemon\";\nstatic const int SOCKET_DELAY_MS = 15000;\n\nPacketData::~PacketData()\n{}\n\nPixmapIdentifier::~PixmapIdentifier()\n{}\n\nNumber::~Number()\n{}\n\nString::~String()\n{}\n\nStringBool::~StringBool()\n{}\n\nPixmapHandle::~PixmapHandle()\n{}\n\nClientList::~ClientList()\n{}\n\nThemeChangeInfo::~ThemeChangeInfo()\n{}\n\nMostUsedPixmaps::~MostUsedPixmaps()\n{}\n\nRequestedPixmap::~RequestedPixmap()\n{}\n\nPacket::Packet(PacketType type, quint64 seq, PacketData *data)\n:\n m_seq (seq),\n m_data (data),\n m_type (type)\n{}\n\nPacket::~Packet()\n{}\n\nvoid Packet::setData(PacketData *data)\n{\n m_data = QSharedPointer(data);\n}\n\nQDataStream &operator<<(QDataStream &stream, const Packet &packet)\n{\n Q_ASSERT(packet.type() != Packet::Unknown);\n\n QByteArray serializedPackageData;\n QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly);\n writePacketData(serializedPackageDataStream, packet);\n stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length());\n\n return stream;\n}\n\nvoid writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet)\n{\n stream << quint32(packet.type());\n stream << packet.sequenceNumber();\n\n switch (packet.type()) {\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n stream << static_cast(packet.data())->string;\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n const ThemeChangeInfo* info = static_cast(packet.data());\n stream << info->themeInheritance << info->themeLibraryNames;\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n stream << static_cast(packet.data())->value;\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n const StringBool *sb = static_cast(packet.data());\n stream << sb->string << sb->b;\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n const PixmapIdentifier *id = static_cast(packet.data());\n stream << *id;\n } break;\n\n case Packet::RequestPixmapPacket: {\n const RequestedPixmap *pixmap = static_cast(packet.data());\n stream << pixmap->priority;\n stream << pixmap->id;\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n const PixmapHandle *h = static_cast(packet.data());\n stream << *h;\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n const MostUsedPixmaps *mostUsedPixmaps = static_cast(packet.data());\n\n stream << mostUsedPixmaps->addedHandles;\n stream << mostUsedPixmaps->removedIdentifiers;\n } break;\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n const ClientList *cl = static_cast(packet.data());\n quint32 clientCount = cl->clients.count();\n stream << clientCount;\n for (uint i = 0; i < clientCount; ++i)\n {\n const ClientInfo &info = cl->clients.at(i);\n stream << info.name;\n quint32 pixmapCount = info.pixmaps.count();\n stream << pixmapCount;\n for (quint32 j = 0; j < pixmapCount; ++j) {\n stream << info.pixmaps.at(j);\n }\n quint32 requestedPixmapCount = info.requestedPixmaps.count();\n stream << requestedPixmapCount;\n for (quint32 j = 0; j < requestedPixmapCount; ++j) {\n stream << info.requestedPixmaps.at(j);\n }\n quint32 releasedPixmapCount = info.releasedPixmaps.count();\n stream << releasedPixmapCount;\n for (quint32 j = 0; j < releasedPixmapCount; ++j) {\n stream << info.releasedPixmaps.at(j);\n }\n }\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nstatic bool waitForAvailableBytes(QDataStream &stream, quint32 count)\n{\n while (stream.device()->bytesAvailable() < count) {\n if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) {\n return false;\n }\n }\n return true;\n}\n\nQDataStream &operator>>(QDataStream &stream, Packet &packet)\n{\n Q_ASSERT(!packet.data());\n\n if (!waitForAvailableBytes(stream, sizeof(quint32))) {\n return stream;\n }\n quint32 length;\n stream >> length;\n if (!waitForAvailableBytes(stream, length)) {\n return stream;\n }\n\n char *raw = new char[length];\n stream.readRawData(raw, length);\n QByteArray serializedPackageData = QByteArray::fromRawData(raw, length);\n QDataStream serializedPackageDataStream(serializedPackageData);\n readPacketData(serializedPackageDataStream, packet);\n\n delete raw;\n\n return stream;\n}\n\nvoid readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet)\n{\n quint32 type = 0;\n quint64 seq = 0;\n\n stream >> type >> seq;\n\n packet.setType(Packet::PacketType(type));\n packet.setSequenceNumber(seq);\n\n switch (packet.type()) {\n\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n QString string;\n stream >> string;\n packet.setData(new String(string));\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n QStringList themeInheritance, themeLibraryNames;\n stream >> themeInheritance >> themeLibraryNames;\n packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames));\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n qint32 priority;\n stream >> priority;\n packet.setData(new Number(priority));\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n QString string;\n stream >> string;\n bool b = false;\n stream >> b;\n packet.setData(new StringBool(string, b));\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new PixmapIdentifier(id));\n } break;\n\n case Packet::RequestPixmapPacket: {\n qint32 priority;\n stream >> priority;\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new RequestedPixmap(id, priority));\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n PixmapHandle h;\n stream >> h;\n packet.setData(new PixmapHandle(h));\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n QList addedHandles;\n stream >> addedHandles;\n\n QList removedIdentifiers;\n stream >> removedIdentifiers;\n\n packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers));\n } break;\n\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n QList clients;\n quint32 clientCount = 0;\n stream >> clientCount;\n while (clientCount) {\n ClientInfo info;\n stream >> info.name;\n quint32 pixmapCount = 0;\n stream >> pixmapCount;\n while (pixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.pixmaps.append(id);\n --pixmapCount;\n }\n quint32 requestedPixmapCount = 0;\n stream >> requestedPixmapCount;\n while (requestedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.requestedPixmaps.append(id);\n --requestedPixmapCount;\n }\n quint32 releasedPixmapCount = 0;\n stream >> releasedPixmapCount;\n while (releasedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.releasedPixmaps.append(id);\n --releasedPixmapCount;\n }\n\n clients.append(info);\n --clientCount;\n }\n packet.setData(new ClientList(clients));\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream << handle.identifier;\n stream << quint64(quintptr(handle.pixmapHandle.xHandle));\n stream << quint64(quintptr(handle.pixmapHandle.eglHandle));\n stream << handle.pixmapHandle.shmHandle;\n stream << handle.pixmapHandle.size;\n stream << (quint64)handle.pixmapHandle.format;\n stream << handle.pixmapHandle.numBytes;\n stream << (bool)handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream >> handle.identifier;\n\n quint64 h;\n stream >> h;\n handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h);\n stream >> h;\n handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h);\n stream >> handle.pixmapHandle.shmHandle;\n stream >> handle.pixmapHandle.size;\n stream >> h;\n handle.pixmapHandle.format = QImage::Format(h);\n stream >> handle.pixmapHandle.numBytes;\n stream >> handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n stream << id.imageId;\n stream << id.size;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n QString imageId;\n stream >> imageId;\n QSize size;\n stream >> size;\n id.imageId = imageId;\n id.size = size;\n return stream;\n}\n\nuint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id)\n{\n using ::qHash;\n\n const uint idHash = qHash(id.imageId);\n const uint widthHash = qHash(id.size.width());\n const uint heightHash = qHash(id.size.height());\n\n \/\/ Twiddle the bits a little, taking a cue from Qt's own qHash() overloads\n return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8);\n}\nChanges: remove bogus Q_ASSERT\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mthemedaemonprotocol.h\"\n#include \n#include \n\nusing namespace M::MThemeDaemonProtocol;\n\nconst QString M::MThemeDaemonProtocol::ServerAddress = \"m.mthemedaemon\";\nstatic const int SOCKET_DELAY_MS = 15000;\n\nPacketData::~PacketData()\n{}\n\nPixmapIdentifier::~PixmapIdentifier()\n{}\n\nNumber::~Number()\n{}\n\nString::~String()\n{}\n\nStringBool::~StringBool()\n{}\n\nPixmapHandle::~PixmapHandle()\n{}\n\nClientList::~ClientList()\n{}\n\nThemeChangeInfo::~ThemeChangeInfo()\n{}\n\nMostUsedPixmaps::~MostUsedPixmaps()\n{}\n\nRequestedPixmap::~RequestedPixmap()\n{}\n\nPacket::Packet(PacketType type, quint64 seq, PacketData *data)\n:\n m_seq (seq),\n m_data (data),\n m_type (type)\n{}\n\nPacket::~Packet()\n{}\n\nvoid Packet::setData(PacketData *data)\n{\n m_data = QSharedPointer(data);\n}\n\nQDataStream &operator<<(QDataStream &stream, const Packet &packet)\n{\n Q_ASSERT(packet.type() != Packet::Unknown);\n\n QByteArray serializedPackageData;\n QDataStream serializedPackageDataStream(&serializedPackageData, QIODevice::WriteOnly);\n writePacketData(serializedPackageDataStream, packet);\n stream.writeBytes(serializedPackageData.constData(), serializedPackageData.length());\n\n return stream;\n}\n\nvoid writePacketData(QDataStream &stream, const M::MThemeDaemonProtocol::Packet &packet)\n{\n stream << quint32(packet.type());\n stream << packet.sequenceNumber();\n\n switch (packet.type()) {\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n stream << static_cast(packet.data())->string;\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n const ThemeChangeInfo* info = static_cast(packet.data());\n stream << info->themeInheritance << info->themeLibraryNames;\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n stream << static_cast(packet.data())->value;\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n const StringBool *sb = static_cast(packet.data());\n stream << sb->string << sb->b;\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n const PixmapIdentifier *id = static_cast(packet.data());\n stream << *id;\n } break;\n\n case Packet::RequestPixmapPacket: {\n const RequestedPixmap *pixmap = static_cast(packet.data());\n stream << pixmap->priority;\n stream << pixmap->id;\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n const PixmapHandle *h = static_cast(packet.data());\n stream << *h;\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n const MostUsedPixmaps *mostUsedPixmaps = static_cast(packet.data());\n\n stream << mostUsedPixmaps->addedHandles;\n stream << mostUsedPixmaps->removedIdentifiers;\n } break;\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n const ClientList *cl = static_cast(packet.data());\n quint32 clientCount = cl->clients.count();\n stream << clientCount;\n for (uint i = 0; i < clientCount; ++i)\n {\n const ClientInfo &info = cl->clients.at(i);\n stream << info.name;\n quint32 pixmapCount = info.pixmaps.count();\n stream << pixmapCount;\n for (quint32 j = 0; j < pixmapCount; ++j) {\n stream << info.pixmaps.at(j);\n }\n quint32 requestedPixmapCount = info.requestedPixmaps.count();\n stream << requestedPixmapCount;\n for (quint32 j = 0; j < requestedPixmapCount; ++j) {\n stream << info.requestedPixmaps.at(j);\n }\n quint32 releasedPixmapCount = info.releasedPixmaps.count();\n stream << releasedPixmapCount;\n for (quint32 j = 0; j < releasedPixmapCount; ++j) {\n stream << info.releasedPixmaps.at(j);\n }\n }\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nstatic bool waitForAvailableBytes(QDataStream &stream, quint32 count)\n{\n while (stream.device()->bytesAvailable() < count) {\n if (!stream.device()->waitForReadyRead(SOCKET_DELAY_MS)) {\n return false;\n }\n }\n return true;\n}\n\nQDataStream &operator>>(QDataStream &stream, Packet &packet)\n{\n if (!waitForAvailableBytes(stream, sizeof(quint32))) {\n return stream;\n }\n quint32 length;\n stream >> length;\n if (!waitForAvailableBytes(stream, length)) {\n return stream;\n }\n\n char *raw = new char[length];\n stream.readRawData(raw, length);\n QByteArray serializedPackageData = QByteArray::fromRawData(raw, length);\n QDataStream serializedPackageDataStream(serializedPackageData);\n readPacketData(serializedPackageDataStream, packet);\n\n delete raw;\n\n return stream;\n}\n\nvoid readPacketData(QDataStream &stream, M::MThemeDaemonProtocol::Packet &packet)\n{\n quint32 type = 0;\n quint64 seq = 0;\n\n stream >> type >> seq;\n\n packet.setType(Packet::PacketType(type));\n packet.setSequenceNumber(seq);\n\n switch (packet.type()) {\n\n \/\/ NULL as data\n case Packet::RequestClearPixmapDirectoriesPacket:\n case Packet::QueryThemeDaemonStatusPacket:\n break;\n\n \/\/ string as data\n case Packet::ErrorPacket:\n case Packet::RequestRegistrationPacket: {\n QString string;\n stream >> string;\n packet.setData(new String(string));\n } break;\n\n \/\/ two string lists as data\n case Packet::ThemeChangedPacket: {\n QStringList themeInheritance, themeLibraryNames;\n stream >> themeInheritance >> themeLibraryNames;\n packet.setData(new ThemeChangeInfo(themeInheritance, themeLibraryNames));\n } break;\n\n case Packet::ProtocolVersionPacket:\n case Packet::ThemeChangeAppliedPacket: {\n qint32 priority;\n stream >> priority;\n packet.setData(new Number(priority));\n } break;\n\n \/\/ stringbool as data\n case Packet::RequestNewPixmapDirectoryPacket: {\n QString string;\n stream >> string;\n bool b = false;\n stream >> b;\n packet.setData(new StringBool(string, b));\n } break;\n\n \/\/ pixmap identifier as data\n case Packet::PixmapUsedPacket:\n case Packet::ReleasePixmapPacket: {\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new PixmapIdentifier(id));\n } break;\n\n case Packet::RequestPixmapPacket: {\n qint32 priority;\n stream >> priority;\n PixmapIdentifier id;\n stream >> id;\n packet.setData(new RequestedPixmap(id, priority));\n } break;\n\n \/\/ pixmap handle as data\n case Packet::PixmapUpdatedPacket: {\n PixmapHandle h;\n stream >> h;\n packet.setData(new PixmapHandle(h));\n } break;\n\n case Packet::MostUsedPixmapsPacket: {\n QList addedHandles;\n stream >> addedHandles;\n\n QList removedIdentifiers;\n stream >> removedIdentifiers;\n\n packet.setData(new MostUsedPixmaps(addedHandles, removedIdentifiers));\n } break;\n\n\n \/\/ client list as data\n case Packet::ThemeDaemonStatusPacket: {\n QList clients;\n quint32 clientCount = 0;\n stream >> clientCount;\n while (clientCount) {\n ClientInfo info;\n stream >> info.name;\n quint32 pixmapCount = 0;\n stream >> pixmapCount;\n while (pixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.pixmaps.append(id);\n --pixmapCount;\n }\n quint32 requestedPixmapCount = 0;\n stream >> requestedPixmapCount;\n while (requestedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.requestedPixmaps.append(id);\n --requestedPixmapCount;\n }\n quint32 releasedPixmapCount = 0;\n stream >> releasedPixmapCount;\n while (releasedPixmapCount) {\n PixmapIdentifier id;\n stream >> id;\n info.releasedPixmaps.append(id);\n --releasedPixmapCount;\n }\n\n clients.append(info);\n --clientCount;\n }\n packet.setData(new ClientList(clients));\n } break;\n\n default:\n \/\/ print out warning\n break;\n }\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream << handle.identifier;\n stream << quint64(quintptr(handle.pixmapHandle.xHandle));\n stream << quint64(quintptr(handle.pixmapHandle.eglHandle));\n stream << handle.pixmapHandle.shmHandle;\n stream << handle.pixmapHandle.size;\n stream << (quint64)handle.pixmapHandle.format;\n stream << handle.pixmapHandle.numBytes;\n stream << (bool)handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapHandle &handle)\n{\n stream >> handle.identifier;\n\n quint64 h;\n stream >> h;\n handle.pixmapHandle.xHandle = (Qt::HANDLE) quintptr(h);\n stream >> h;\n handle.pixmapHandle.eglHandle = (Qt::HANDLE) quintptr(h);\n stream >> handle.pixmapHandle.shmHandle;\n stream >> handle.pixmapHandle.size;\n stream >> h;\n handle.pixmapHandle.format = QImage::Format(h);\n stream >> handle.pixmapHandle.numBytes;\n stream >> handle.pixmapHandle.directMap;\n return stream;\n}\n\nQDataStream &operator<<(QDataStream &stream, const M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n stream << id.imageId;\n stream << id.size;\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, M::MThemeDaemonProtocol::PixmapIdentifier &id)\n{\n QString imageId;\n stream >> imageId;\n QSize size;\n stream >> size;\n id.imageId = imageId;\n id.size = size;\n return stream;\n}\n\nuint M::MThemeDaemonProtocol::qHash(const PixmapIdentifier &id)\n{\n using ::qHash;\n\n const uint idHash = qHash(id.imageId);\n const uint widthHash = qHash(id.size.width());\n const uint heightHash = qHash(id.size.height());\n\n \/\/ Twiddle the bits a little, taking a cue from Qt's own qHash() overloads\n return idHash ^ (widthHash << 8) ^ (widthHash >> 24) ^ (heightHash << 24) ^ (heightHash >> 8);\n}\n<|endoftext|>"} {"text":"#ifndef EBITEN_GAME_GRAPHICS_AFFINE_MATRIX_HPP\n#define EBITEN_GAME_GRAPHICS_AFFINE_MATRIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace ebiten {\nnamespace game {\nnamespace graphics {\n\ntemplate\nclass affine_matrix : private boost::noncopyable {\n BOOST_STATIC_ASSERT(0 < Dimension);\nprivate:\n static std::size_t const size = Dimension * (Dimension - 1);\n typedef std::array elements_type;\n elements_type elements_;\npublic:\n \/\/ TODO: accepts iterators\n \/\/ TODO: constructor's arugments?\n template\n affine_matrix(Elements const& elements) {\n assert(static_cast(boost::size(elements)) <= size);\n this->elements_.fill(0);\n std::copy(std::begin(elements), std::end(elements), this->elements_.begin());\n }\n template\n Float\n element() const {\n BOOST_STATIC_ASSERT(I < Dimension);\n BOOST_STATIC_ASSERT(J < Dimension);\n return this->element(boost::mpl::size_t(), boost::mpl::size_t());\n }\n template\n Float\n set_element(Float element) {\n BOOST_STATIC_ASSERT(I < Dimension - 1);\n BOOST_STATIC_ASSERT(J < Dimension);\n return this->elements_[I * Dimension + J] = element;\n }\n bool\n is_identity() const {\n typename elements_type::const_iterator it = this->elements_.begin();\n for (std::size_t i = 0; i < Dimension - 1; ++i) {\n for (std::size_t j = 0; j < Dimension; ++j, ++it) {\n if (i == j) {\n if (*it != 1) {\n return false;\n }\n } else {\n if (*it != 0) {\n return false;\n }\n }\n }\n }\n return true;\n }\nprivate:\n Float\n element(std::size_t i, std::size_t j) const {\n return this->elements_[i * Dimension + j];\n }\n Float\n element(boost::mpl::size_t, std::size_t) const {\n return 0;\n }\n Float\n element(boost::mpl::size_t, boost::mpl::size_t) const {\n return 1;\n }\n};\n\n}\n}\n}\n\n#ifdef EBITEN_TEST\n\nnamespace ebiten {\nnamespace game {\nnamespace graphics {\n\nBOOST_AUTO_TEST_CASE(affine_matrix_element) {\n affine_matrix m((double[]){1, 2, 3});\n BOOST_CHECK_EQUAL(1, (m.element<0, 0>()));\n BOOST_CHECK_EQUAL(2, (m.element<0, 1>()));\n BOOST_CHECK_EQUAL(3, (m.element<0, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<0, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 2>()));\n BOOST_CHECK_EQUAL(1, (m.element<3, 3>()));\n m.set_element<1, 0>(4);\n m.set_element<1, 1>(5);\n m.set_element<2, 3>(6);\n BOOST_CHECK_EQUAL(1, (m.element<0, 0>()));\n BOOST_CHECK_EQUAL(2, (m.element<0, 1>()));\n BOOST_CHECK_EQUAL(3, (m.element<0, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<0, 3>()));\n BOOST_CHECK_EQUAL(4, (m.element<1, 0>()));\n BOOST_CHECK_EQUAL(5, (m.element<1, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 2>()));\n BOOST_CHECK_EQUAL(6, (m.element<2, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 2>()));\n BOOST_CHECK_EQUAL(1, (m.element<3, 3>()));\n}\n\nBOOST_AUTO_TEST_CASE(affine_matrix_is_identity) {\n affine_matrix m1((double[]){1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0});\n BOOST_CHECK(m1.is_identity());\n affine_matrix m2((double[]){1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0});\n BOOST_CHECK(!m2.is_identity());\n}\n\n}\n}\n}\n\n#endif\n\n#endif\nRemoved #include#ifndef EBITEN_GAME_GRAPHICS_AFFINE_MATRIX_HPP\n#define EBITEN_GAME_GRAPHICS_AFFINE_MATRIX_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace ebiten {\nnamespace game {\nnamespace graphics {\n\ntemplate\nclass affine_matrix : private boost::noncopyable {\n BOOST_STATIC_ASSERT(0 < Dimension);\nprivate:\n static std::size_t const size = Dimension * (Dimension - 1);\n typedef std::array elements_type;\n elements_type elements_;\npublic:\n \/\/ TODO: accepts iterators\n \/\/ TODO: constructor's arugments?\n template\n explicit\n affine_matrix(Elements const& elements) {\n assert(static_cast(boost::size(elements)) <= size);\n this->elements_.fill(0);\n std::copy(std::begin(elements), std::end(elements), this->elements_.begin());\n }\n template\n Float\n element() const {\n BOOST_STATIC_ASSERT(I < Dimension);\n BOOST_STATIC_ASSERT(J < Dimension);\n return this->element_();\n }\n template\n Float\n set_element(Float element) {\n BOOST_STATIC_ASSERT(I < Dimension - 1);\n BOOST_STATIC_ASSERT(J < Dimension);\n return this->elements_[I * Dimension + J] = element;\n }\n bool\n is_identity() const {\n typename elements_type::const_iterator it = this->elements_.begin();\n for (std::size_t i = 0; i < Dimension - 1; ++i) {\n for (std::size_t j = 0; j < Dimension; ++j, ++it) {\n if (i == j) {\n if (*it != 1) {\n return false;\n }\n } else {\n if (*it != 0) {\n return false;\n }\n }\n }\n }\n return true;\n }\nprivate:\n template\n Float\n element_() const {\n if (I == Dimension - 1) {\n if (J == Dimension - 1) {\n return 1;\n }\n return 0;\n }\n return this->elements_[I * Dimension + J];\n }\n};\n\n}\n}\n}\n\n#ifdef EBITEN_TEST\n\nnamespace ebiten {\nnamespace game {\nnamespace graphics {\n\nBOOST_AUTO_TEST_CASE(affine_matrix_element) {\n affine_matrix m((double[]){1, 2, 3});\n BOOST_CHECK_EQUAL(1, (m.element<0, 0>()));\n BOOST_CHECK_EQUAL(2, (m.element<0, 1>()));\n BOOST_CHECK_EQUAL(3, (m.element<0, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<0, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 2>()));\n BOOST_CHECK_EQUAL(1, (m.element<3, 3>()));\n m.set_element<1, 0>(4);\n m.set_element<1, 1>(5);\n m.set_element<2, 3>(6);\n BOOST_CHECK_EQUAL(1, (m.element<0, 0>()));\n BOOST_CHECK_EQUAL(2, (m.element<0, 1>()));\n BOOST_CHECK_EQUAL(3, (m.element<0, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<0, 3>()));\n BOOST_CHECK_EQUAL(4, (m.element<1, 0>()));\n BOOST_CHECK_EQUAL(5, (m.element<1, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 2>()));\n BOOST_CHECK_EQUAL(0, (m.element<1, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<2, 2>()));\n BOOST_CHECK_EQUAL(6, (m.element<2, 3>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 0>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 1>()));\n BOOST_CHECK_EQUAL(0, (m.element<3, 2>()));\n BOOST_CHECK_EQUAL(1, (m.element<3, 3>()));\n}\n\nBOOST_AUTO_TEST_CASE(affine_matrix_is_identity) {\n affine_matrix m1((double[]){1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0});\n BOOST_CHECK(m1.is_identity());\n affine_matrix m2((double[]){1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0});\n BOOST_CHECK(!m2.is_identity());\n}\n\n}\n}\n}\n\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: share.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 22:23:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"uno\/mapping.h\"\n\n#include \n#include \n#include \n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\n void dummy_can_throw_anything( char const * );\n\n\n\/\/ ----- following decl from libstdc++-v3\/libsupc++\/unwind-cxx.h and unwind.h\n\nstruct _Unwind_Exception\n{\n unsigned exception_class __attribute__((__mode__(__DI__)));\n void * exception_cleanup;\n unsigned private_1 __attribute__((__mode__(__word__)));\n unsigned private_2 __attribute__((__mode__(__word__)));\n} __attribute__((__aligned__));\n\nstruct __cxa_exception\n{\n ::std::type_info *exceptionType;\n void (*exceptionDestructor)(void *);\n\n ::std::unexpected_handler unexpectedHandler;\n ::std::terminate_handler terminateHandler;\n\n __cxa_exception *nextException;\n\n int handlerCount;\n\n int handlerSwitchValue;\n const unsigned char *actionRecord;\n const unsigned char *languageSpecificData;\n void *catchTemp;\n void *adjustedPtr;\n\n _Unwind_Exception unwindHeader;\n};\n\nextern \"C\" void *__cxa_allocate_exception(\n std::size_t thrown_size ) throw();\nextern \"C\" void __cxa_throw (\n void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));\n\nstruct __cxa_eh_globals\n{\n __cxa_exception *caughtExceptions;\n unsigned int uncaughtExceptions;\n};\nextern \"C\" __cxa_eh_globals *__cxa_get_globals () throw();\n\n\/\/ -----\n\n\/\/==================================================================================================\nvoid raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\/\/==================================================================================================\nvoid fillUnoException(\n __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );\n}\nINTEGRATION: CWS changefileheader (1.5.170); FILE MERGED 2008\/03\/28 16:30:13 rt 1.5.170.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: share.hxx,v $\n * $Revision: 1.6 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#include \"uno\/mapping.h\"\n\n#include \n#include \n#include \n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\n void dummy_can_throw_anything( char const * );\n\n\n\/\/ ----- following decl from libstdc++-v3\/libsupc++\/unwind-cxx.h and unwind.h\n\nstruct _Unwind_Exception\n{\n unsigned exception_class __attribute__((__mode__(__DI__)));\n void * exception_cleanup;\n unsigned private_1 __attribute__((__mode__(__word__)));\n unsigned private_2 __attribute__((__mode__(__word__)));\n} __attribute__((__aligned__));\n\nstruct __cxa_exception\n{\n ::std::type_info *exceptionType;\n void (*exceptionDestructor)(void *);\n\n ::std::unexpected_handler unexpectedHandler;\n ::std::terminate_handler terminateHandler;\n\n __cxa_exception *nextException;\n\n int handlerCount;\n\n int handlerSwitchValue;\n const unsigned char *actionRecord;\n const unsigned char *languageSpecificData;\n void *catchTemp;\n void *adjustedPtr;\n\n _Unwind_Exception unwindHeader;\n};\n\nextern \"C\" void *__cxa_allocate_exception(\n std::size_t thrown_size ) throw();\nextern \"C\" void __cxa_throw (\n void *thrown_exception, std::type_info *tinfo, void (*dest) (void *) ) __attribute__((noreturn));\n\nstruct __cxa_eh_globals\n{\n __cxa_exception *caughtExceptions;\n unsigned int uncaughtExceptions;\n};\nextern \"C\" __cxa_eh_globals *__cxa_get_globals () throw();\n\n\/\/ -----\n\n\/\/==================================================================================================\nvoid raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\/\/==================================================================================================\nvoid fillUnoException(\n __cxa_exception * header, uno_Any *, uno_Mapping * pCpp2Uno );\n}\n<|endoftext|>"} {"text":"\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cast.h\"\n#include \"mlp.hpp\"\n#include \"mlp_impl.h\"\n\n\/*\nextern int EF_ALIGNMENT = 0;\nextern int EF_PROTECT_BELOW = 0;\nextern int EF_PROTECT_FREE = 0;\nextern int EF_ALLOW_MALLOC_0 = 1;\nextern int EF_FILL = 1922;\n*\/\n\nnamespace { struct hack_t; }\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nmlp * convertHackToMlp ( const hack_t & hack );\nvoid freeClassifiers( mlp * classifiers[], int size );\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nMatFloat convertCVToMatFloat ( const cv::Mat_ & input );\ncv::Mat_ convertMatFloatToCV( MatFloat input );\nvoid allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );\nvoid freeResponseMaps( MatFloat * responseMaps[], int size );\n\n\nnamespace {\n \n struct hack_t {\n int m_visibleLandmarks_size;\n int m_mapSize;\n \n cv::Mat_ shape;\n cv::Mat_ alignedImage;\n std::vector > m_classifiers;\n std::vector > responseMaps;\n \n template \n void serialize( MT0 & archiver, unsigned int ) {\n GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );\n GEL_EXPORT_VAR( archiver, m_mapSize );\n GEL_EXPORT_VAR( archiver, shape );\n GEL_EXPORT_VAR( archiver, alignedImage );\n GEL_EXPORT_VAR( archiver, m_classifiers );\n GEL_EXPORT_VAR( archiver, responseMaps ); \n } \/\/ serialize\n \n }; \/\/ struct hack_t\n \n class conductor_t {\n public:\n int id;\n hack_t hack;\n std::ifstream dumpStream;\n boost::archive::binary_iarchive importer;\n\n public:\n \n conductor_t() : id(0), dumpStream(\"response_dumps.bin\", std::ios::in | std::ios::binary ), importer(dumpStream) {\n \n }; \/\/ conductor_t\n \n }; \/\/ conductor_t\n\n} \/\/ unnamed namespace \n\n\n\nmlp *\nconvertHackToMlp ( const hack_t & hack )\n{\n assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());\n assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());\n \n mlp * result;\n result = reinterpret_cast( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );\n\n \/\/ we export each classifier\n for (int q=0; q & input )\n{\n MatChar result = CreateMatChar( input.rows, input.cols );\n\n for ( int q=0; q & input )\n{\n MatFloat result = CreateMatFloat( input.rows, input.cols );\n \n for ( int q=0; q convertMatFloatToCV( MatFloat input )\n{\n cv::Mat_ result( input.rows, input.cols );\n \n for ( int q=0; q\nauto\nmicroseconds( T0 t0 ) -> decltype(std::chrono::duration_cast(t0).count())\n{\n return std::chrono::duration_cast(t0).count();\n}\n\n\nint main()\n{\n conductor_t conductor;\n int fail = 0;\n long int elapsed_time = 0;\n \n\n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); \n ((conductor.id != -1) and (conductor.id != 25));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n \/\/ here comes the function call\n {\n \/\/ preparing the inputs\n MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);\n MatFloat shape = convertCVToMatFloat(conductor.hack.shape);\n mlp * m_classifiers = convertHackToMlp(conductor.hack);\n MatFloat * responseMaps;\n allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );\n\n auto start = std::chrono::high_resolution_clock::now();\n calculateMaps(\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n alignedImage,\n shape,\n m_classifiers,\n &responseMaps\n );\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time = microseconds(end - start); \n \n \/\/ releasing the inputs\n freeMatChar(&alignedImage);\n freeMatFloat(&shape);\n freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());\n\n \/\/ converting the outputs\n std::vector< cv::Mat_ > calculatedResults;\n for (int q=0; q nextResult;\n nextResult = convertMatFloatToCV( responseMaps[q] );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q 0.5 )\n {\n fail++;\n std::cout << \"cv::norm( conductor.hack.responseMaps[\" << q << \"] - calculatedResults[\" << q << \"] ) = \"\n << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;\n \n }\n \n \/\/ PRINT(fail);\n int tolerance = 49 * conductor.id * 0.005 + 3;\n \/\/ PRINT(tolerance); \n assert(fail < tolerance);\n }\n \n \/\/ releasing the outputs\n freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );\n\n }\n \/\/ here comes the test\n \/\/ PRINT(cv::norm( ));\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl; \n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n \n return EXIT_SUCCESS;\n}\n\n\n\n\/\/ LuM end of file\ntesting the mlp\/\/ UjoImro, 2013\n\/\/ Experimental code for the CARP Project\n\/\/ Copyright (c) RealEyes, 2013\n\/\/ This version tests the responseMap calculation with input dumps\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"cast.h\"\n#include \"mlp.hpp\"\n#include \"mlp_impl.h\"\n\n\nextern int EF_ALIGNMENT = 0;\nextern int EF_PROTECT_BELOW = 0;\nextern int EF_PROTECT_FREE = 0;\nextern int EF_ALLOW_MALLOC_0 = 1;\nextern int EF_FILL = 1922;\n\nnamespace { struct hack_t; }\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nmlp * convertHackToMlp ( const hack_t & hack );\nvoid freeClassifiers( mlp * classifiers[], int size );\nMatChar convertCVToMatChar ( const cv::Mat_ & input );\nMatFloat convertCVToMatFloat ( const cv::Mat_ & input );\ncv::Mat_ convertMatFloatToCV( MatFloat input );\nvoid allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] );\nvoid freeResponseMaps( MatFloat * responseMaps[], int size );\n\n\nnamespace {\n \n struct hack_t {\n int m_visibleLandmarks_size;\n int m_mapSize;\n \n cv::Mat_ shape;\n cv::Mat_ alignedImage;\n std::vector > m_classifiers;\n std::vector > responseMaps;\n \n template \n void serialize( MT0 & archiver, unsigned int ) {\n GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size );\n GEL_EXPORT_VAR( archiver, m_mapSize );\n GEL_EXPORT_VAR( archiver, shape );\n GEL_EXPORT_VAR( archiver, alignedImage );\n GEL_EXPORT_VAR( archiver, m_classifiers );\n GEL_EXPORT_VAR( archiver, responseMaps ); \n } \/\/ serialize\n \n }; \/\/ struct hack_t\n \n class conductor_t {\n public:\n int id;\n hack_t hack;\n std::ifstream dumpStream;\n boost::archive::binary_iarchive importer;\n\n public:\n \n conductor_t() : id(0), dumpStream(\"response_dumps.bin\", std::ios::in | std::ios::binary ), importer(dumpStream) {\n \n }; \/\/ conductor_t\n \n }; \/\/ conductor_t\n\n} \/\/ unnamed namespace \n\n\n\nmlp *\nconvertHackToMlp ( const hack_t & hack )\n{\n assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size());\n assert(hack.m_visibleLandmarks_size==hack.responseMaps.size());\n \n mlp * result;\n result = reinterpret_cast( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) );\n\n \/\/ we export each classifier\n for (int q=0; q & input )\n{\n MatChar result = CreateMatChar( input.rows, input.cols );\n\n for ( int q=0; q & input )\n{\n MatFloat result = CreateMatFloat( input.rows, input.cols );\n \n for ( int q=0; q convertMatFloatToCV( MatFloat input )\n{\n cv::Mat_ result( input.rows, input.cols );\n \n for ( int q=0; q\nauto\nmicroseconds( T0 t0 ) -> decltype(std::chrono::duration_cast(t0).count())\n{\n return std::chrono::duration_cast(t0).count();\n}\n\n\nint main()\n{\n conductor_t conductor;\n int fail = 0;\n long int elapsed_time = 0;\n \n\n for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); \n ((conductor.id != -1) and (conductor.id != 25));\n \/\/ conductor.id != -1;\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)\n )\n {\n PRINT(conductor.id);\n conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n\n \/\/ here comes the function call\n {\n \/\/ preparing the inputs\n MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage);\n MatFloat shape = convertCVToMatFloat(conductor.hack.shape);\n mlp * m_classifiers = convertHackToMlp(conductor.hack);\n MatFloat * responseMaps;\n allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps );\n\n auto start = std::chrono::high_resolution_clock::now();\n calculateMaps(\n conductor.hack.m_visibleLandmarks_size,\n conductor.hack.m_mapSize,\n alignedImage,\n shape,\n m_classifiers,\n &responseMaps\n );\n auto end = std::chrono::high_resolution_clock::now();\n elapsed_time = microseconds(end - start); \n \n \/\/ releasing the inputs\n freeMatChar(&alignedImage);\n freeMatFloat(&shape);\n freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size());\n\n \/\/ converting the outputs\n std::vector< cv::Mat_ > calculatedResults;\n for (int q=0; q nextResult;\n nextResult = convertMatFloatToCV( responseMaps[q] );\n calculatedResults.push_back(nextResult); \n }\n \n \/\/ testing the output\n for (int q=0; q 0.5 )\n \/\/ {\n \/\/ fail++;\n \/\/ std::cout << \"cv::norm( conductor.hack.responseMaps[\" << q << \"] - calculatedResults[\" << q << \"] ) = \"\n \/\/ << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;\n \n \/\/ }\n \n \/\/ PRINT(fail);\n int tolerance = 49 * conductor.id * 0.005 + 3;\n \/\/ PRINT(tolerance); \n assert(fail < tolerance);\n }\n \n \/\/ releasing the outputs\n freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size );\n\n }\n \/\/ here comes the test\n \/\/ PRINT(cv::norm( ));\n }\n \n std::cout << \"total elapsed time = \" << elapsed_time \/ 1000000. << \" s.\" << std::endl; \n \/\/conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);\n \n return EXIT_SUCCESS;\n}\n\n\n\n\/\/ LuM end of file\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"kernel.h\"\n#include \"coverage.h\"\n#include \"columndefinition.h\"\n#include \"table.h\"\n#include \"attributerecord.h\"\n#include \"polygon.h\"\n#include \"geometry.h\"\n#include \"feature.h\"\n#include \"featurecoverage.h\"\n#include \"symboltable.h\"\n#include \"OperationExpression.h\"\n#include \"operationmetadata.h\"\n#include \"operation.h\"\n#include \"operationhelper.h\"\n#include \"operationhelperfeatures.h\"\n#include \"commandhandler.h\"\n#include \"featureiterator.h\"\n#include \"selectionfeatures.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nSelectionFeatures::SelectionFeatures()\n{\n}\n\nSelectionFeatures::SelectionFeatures(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nSelectionFeatures::~SelectionFeatures()\n{\n}\n\n\nbool SelectionFeatures::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n IFeatureCoverage outputFC = _outputObj.get();\n IFeatureCoverage inputFC = _inputObj.get();\n\n SubSetAsyncFunc selection = [&](const std::vector& subset ) -> bool {\n FeatureIterator iterIn(inputFC, subset);\n\n AttributeRecord rec;\n if ( _attribColumn != \"\")\n rec = AttributeRecord(inputFC->attributeTable(), FEATUREIDCOLUMN);\n SPAttributeRecord attrib (new AttributeRecord(_attTable, FEATUREIDCOLUMN));\n quint64 v_in = 0;\n for_each(iterIn, iterIn.end(), [&](SPFeatureI feature){\n QVariant v;\n if ( rec.isValid()) {\n SPFeatureI feature = *iterIn;\n v_in = feature->value(FEATUREIDCOLUMN).toULongLong();\n v = rec.cellByKey(v_in,_attribColumn);\n } else {\n v = v_in;\n }\n SPFeatureI newFeature = outputFC->newFeatureFrom(feature);\n if ( !newFeature.isNull()) {\n newFeature->attributeRecord(attrib);\n _attTable->record(NEW_RECORD,{newFeature->featureid(), v});\n }\n\n ++iterIn;\n }\n );\n return true;\n };\n ctx->_threaded = false;\n bool resource = OperationHelperFeatures::execute(ctx,selection, inputFC, outputFC, _attTable);\n\n if ( resource && ctx != 0) {\n outputFC->attributeTable(_attTable);\n QVariant value;\n value.setValue(outputFC);\n ctx->addOutput(symTable, value, outputFC->name(), itFEATURE,outputFC->source());\n }\n return true;\n}\n\nIlwis::OperationImplementation *SelectionFeatures::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new SelectionFeatures(metaid, expr);\n}\n\nIlwis::OperationImplementation::State SelectionFeatures::prepare(ExecutionContext *, const SymbolTable &)\n{\n IlwisTypes inputType = itFEATURE;\n QString fc = _expression.parm(0).value();\n if (!_inputObj.prepare(fc, inputType)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,fc,\"\");\n return sPREPAREFAILED;\n }\n IFeatureCoverage inputFC = _inputObj.get();\n quint64 copylist = itCOORDSYSTEM;\n\n\n QString selector = _expression.parm(1).value();\n selector = selector.remove('\"');\n\n int index = selector.indexOf(\"box=\");\n Box2D box;\n if ( index != -1) {\n QString crdlist = \"box(\" + selector.mid(index+4) + \")\";\n _box = Box3D(crdlist);\n copylist |= itDOMAIN | itTABLE;\n }\n index = selector.indexOf(\"polygon=\");\n if ( index != -1)\n {\n \/\/TODO\n copylist |= itDOMAIN | itTABLE;\n }\n index = selector.indexOf(\"attribute=\");\n if ( index != -1 ) {\n if (! inputFC->attributeTable().isValid()) {\n ERROR2(ERR_NO_FOUND2,\"attribute-table\", \"coverage\");\n return sPREPAREFAILED;\n }\n _attribColumn = selector.mid(index+10);\n copylist |= itENVELOPE;\n }\n\n _outputObj = OperationHelperFeatures::initialize(_inputObj,inputType, copylist);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output coverage\");\n return sPREPAREFAILED;\n }\n QString outputName = _expression.parm(0,false).value();\n if ( outputName != sUNDEF)\n _outputObj->setName(outputName);\n\n if ( _attribColumn != \"\") {\n QString url = \"ilwis:\/\/internal\/\" + outputName;\n Resource resource(url, itFLATTABLE);\n _attTable.prepare(resource);\n IDomain covdom;\n if (!covdom.prepare(\"count\")){\n return sPREPAREFAILED;\n }\n _attTable->addColumn(FEATUREIDCOLUMN,covdom);\n _attTable->addColumn(_attribColumn, inputFC->attributeTable()->columndefinition(_attribColumn).datadef().domain());\n }\n if ( (_box.isValid() && !_box.isNull()) == 0) {\n \/\/TODO selections in features on bounding box\n }\n return sPREPARED;\n}\n\nquint64 SelectionFeatures::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/selection\");\n Resource resource(QUrl(url), itOPERATIONMETADATA);\n resource.addProperty(\"namespace\",\"ilwis\");\n resource.addProperty(\"longname\",\"selection\");\n resource.addProperty(\"syntax\",\"selection(featurecoverage,selection-definition)\");\n resource.addProperty(\"description\",TR(\"the operation select parts of the spatial extent or attributes to create a 'smaller' coverage\"));\n resource.addProperty(\"inparameters\",\"2\");\n resource.addProperty(\"pin_1_type\", itFEATURE);\n resource.addProperty(\"pin_1_name\", TR(\"input rastercoverage\"));\n resource.addProperty(\"pin_1_desc\",TR(\"input rastercoverage with a domain as specified by the selection\"));\n resource.addProperty(\"pin_2_type\", itSTRING);\n resource.addProperty(\"pin_2_name\", TR(\"selection-definition\"));\n resource.addProperty(\"pin_2_desc\",TR(\"Selection can either be attribute, layer index or area definition (e.g. box)\"));\n resource.addProperty(\"pout_1_type\", itFEATURE);\n resource.addProperty(\"pout_1_name\", TR(\"rastercoverage were the selection has been applied\"));\n resource.addProperty(\"pout_1_desc\",TR(\"\"));\n resource.prepare();\n url += \"=\" + QString::number(resource.id());\n resource.setUrl(url);\n\n mastercatalog()->addItems({resource});\n return resource.id();\n\n}\nchanges due to changes in the way how features work#include \n#include \n#include \n#include \n#include \"kernel.h\"\n#include \"coverage.h\"\n#include \"columndefinition.h\"\n#include \"table.h\"\n#include \"attributerecord.h\"\n#include \"polygon.h\"\n#include \"geometry.h\"\n#include \"feature.h\"\n#include \"featurecoverage.h\"\n#include \"symboltable.h\"\n#include \"OperationExpression.h\"\n#include \"operationmetadata.h\"\n#include \"operation.h\"\n#include \"operationhelper.h\"\n#include \"operationhelperfeatures.h\"\n#include \"commandhandler.h\"\n#include \"featureiterator.h\"\n#include \"selectionfeatures.h\"\n\nusing namespace Ilwis;\nusing namespace BaseOperations;\n\nSelectionFeatures::SelectionFeatures()\n{\n}\n\nSelectionFeatures::SelectionFeatures(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr)\n{\n}\n\nSelectionFeatures::~SelectionFeatures()\n{\n}\n\n\nbool SelectionFeatures::execute(ExecutionContext *ctx, SymbolTable &symTable)\n{\n if (_prepState == sNOTPREPARED)\n if((_prepState = prepare(ctx, symTable)) != sPREPARED)\n return false;\n\n IFeatureCoverage outputFC = _outputObj.get();\n IFeatureCoverage inputFC = _inputObj.get();\n\n SubSetAsyncFunc selection = [&](const std::vector& subset ) -> bool {\n FeatureIterator iterIn(inputFC, subset);\n\n for_each(iterIn, iterIn.end(), [&](SPFeatureI feature){\n QVariant v = feature->cell(_attribColumn);\n SPFeatureI newFeature = outputFC->newFeatureFrom(feature);\n _attTable->record(NEW_RECORD,{newFeature->featureid(), v});\n\n ++iterIn;\n }\n );\n return true;\n };\n ctx->_threaded = false;\n bool resource = OperationHelperFeatures::execute(ctx,selection, inputFC, outputFC, _attTable);\n\n if ( resource && ctx != 0) {\n outputFC->attributeTable(_attTable);\n QVariant value;\n value.setValue(outputFC);\n ctx->addOutput(symTable, value, outputFC->name(), itFEATURE,outputFC->source());\n }\n return true;\n}\n\nIlwis::OperationImplementation *SelectionFeatures::create(quint64 metaid, const Ilwis::OperationExpression &expr)\n{\n return new SelectionFeatures(metaid, expr);\n}\n\nIlwis::OperationImplementation::State SelectionFeatures::prepare(ExecutionContext *, const SymbolTable &)\n{\n IlwisTypes inputType = itFEATURE;\n QString fc = _expression.parm(0).value();\n if (!_inputObj.prepare(fc, inputType)) {\n ERROR2(ERR_COULD_NOT_LOAD_2,fc,\"\");\n return sPREPAREFAILED;\n }\n IFeatureCoverage inputFC = _inputObj.get();\n quint64 copylist = itCOORDSYSTEM;\n\n\n QString selector = _expression.parm(1).value();\n selector = selector.remove('\"');\n\n int index = selector.indexOf(\"box=\");\n Box2D box;\n if ( index != -1) {\n QString crdlist = \"box(\" + selector.mid(index+4) + \")\";\n _box = Box3D(crdlist);\n copylist |= itDOMAIN | itTABLE;\n }\n index = selector.indexOf(\"polygon=\");\n if ( index != -1)\n {\n \/\/TODO\n copylist |= itDOMAIN | itTABLE;\n }\n index = selector.indexOf(\"attribute=\");\n if ( index != -1 ) {\n if (! inputFC->attributeTable().isValid()) {\n ERROR2(ERR_NO_FOUND2,\"attribute-table\", \"coverage\");\n return sPREPAREFAILED;\n }\n _attribColumn = selector.mid(index+10);\n copylist |= itENVELOPE;\n }\n\n _outputObj = OperationHelperFeatures::initialize(_inputObj,inputType, copylist);\n if ( !_outputObj.isValid()) {\n ERROR1(ERR_NO_INITIALIZED_1, \"output coverage\");\n return sPREPAREFAILED;\n }\n QString outputName = _expression.parm(0,false).value();\n if ( outputName != sUNDEF)\n _outputObj->setName(outputName);\n\n if ( _attribColumn != \"\") {\n QString url = \"ilwis:\/\/internal\/\" + outputName;\n Resource resource(url, itFLATTABLE);\n _attTable.prepare(resource);\n IDomain covdom;\n if (!covdom.prepare(\"count\")){\n return sPREPAREFAILED;\n }\n _attTable->addColumn(FEATUREIDCOLUMN,covdom);\n _attTable->addColumn(_attribColumn, inputFC->attributeTable()->columndefinition(_attribColumn).datadef().domain());\n }\n if ( (_box.isValid() && !_box.isNull()) == 0) {\n \/\/TODO selections in features on bounding box\n }\n return sPREPARED;\n}\n\nquint64 SelectionFeatures::createMetadata()\n{\n QString url = QString(\"ilwis:\/\/operations\/selection\");\n Resource resource(QUrl(url), itOPERATIONMETADATA);\n resource.addProperty(\"namespace\",\"ilwis\");\n resource.addProperty(\"longname\",\"selection\");\n resource.addProperty(\"syntax\",\"selection(featurecoverage,selection-definition)\");\n resource.addProperty(\"description\",TR(\"the operation select parts of the spatial extent or attributes to create a 'smaller' coverage\"));\n resource.addProperty(\"inparameters\",\"2\");\n resource.addProperty(\"pin_1_type\", itFEATURE);\n resource.addProperty(\"pin_1_name\", TR(\"input rastercoverage\"));\n resource.addProperty(\"pin_1_desc\",TR(\"input rastercoverage with a domain as specified by the selection\"));\n resource.addProperty(\"pin_2_type\", itSTRING);\n resource.addProperty(\"pin_2_name\", TR(\"selection-definition\"));\n resource.addProperty(\"pin_2_desc\",TR(\"Selection can either be attribute, layer index or area definition (e.g. box)\"));\n resource.addProperty(\"pout_1_type\", itFEATURE);\n resource.addProperty(\"pout_1_name\", TR(\"rastercoverage were the selection has been applied\"));\n resource.addProperty(\"pout_1_desc\",TR(\"\"));\n resource.prepare();\n url += \"=\" + QString::number(resource.id());\n resource.setUrl(url);\n\n mastercatalog()->addItems({resource});\n return resource.id();\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain 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#include \"scheduling\/request-pool-service.h\"\n\n#include \n#include \n\n#include \"common\/logging.h\"\n#include \"rpc\/thrift-util.h\"\n#include \"util\/jni-util.h\"\n#include \"util\/parse-util.h\"\n\nusing namespace std;\nusing namespace impala;\n\nDEFINE_string(fair_scheduler_allocation_path, \"\", \"Path to the fair scheduler \"\n \"allocation file (fair-scheduler.xml).\");\nDEFINE_string(llama_site_path, \"\", \"Path to the Llama configuration file \"\n \"(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.\");\n\n\/\/ The default_pool parameters are used if fair scheduler allocation and Llama\n\/\/ configuration files are not provided.\nDEFINE_int64(default_pool_max_requests, -1, \"Maximum number of concurrent outstanding \"\n \"requests allowed to run before queueing incoming requests. A negative value \"\n \"indicates no limit. 0 indicates no requests will be admitted. Ignored if \"\n \"fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_string(default_pool_mem_limit, \"\", \"Maximum amount of memory that all \"\n \"outstanding requests in this pool may use before new requests to this pool\"\n \" are queued. Specified as a number of bytes ('[bB]?'), megabytes \"\n \"('[mM]'), gigabytes ('[gG]'), or percentage of the physical memory \"\n \"('%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is \"\n \"given. Ignored if fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_int64(default_pool_max_queued, 0, \"Maximum number of requests allowed to be \"\n \"queued before rejecting requests. A negative value or 0 indicates requests \"\n \"will always be rejected once the maximum number of concurrent requests are \"\n \"executing. Ignored if fair_scheduler_config_path and \"\n \"llama_site_path are set.\");\n\n\/\/ Flags to disable the pool limits for all pools.\nDEFINE_bool(disable_pool_mem_limits, false, \"Disables all per-pool mem limits.\");\nDEFINE_bool(disable_pool_max_requests, false, \"Disables all per-pool limits on the \"\n \"maximum number of running requests.\");\n\nDECLARE_bool(enable_rm);\n\n\/\/ Pool name used when the configuration files are not specified.\nconst string DEFAULT_POOL_NAME = \"default-pool\";\n\nRequestPoolService::RequestPoolService() {\n if (FLAGS_fair_scheduler_allocation_path.empty() &&\n FLAGS_llama_site_path.empty()) {\n if (FLAGS_enable_rm) {\n LOG(ERROR) << \"If resource management is enabled, -fair_scheduler_allocation_path \"\n << \"is required.\";\n exit(1);\n }\n default_pool_only_ = true;\n bool is_percent; \/\/ not used\n int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,\n &is_percent);\n \/\/ -1 indicates an error occurred\n if (bytes_limit < 0) {\n LOG(ERROR) << \"Unable to parse default pool mem limit from '\"\n << FLAGS_default_pool_mem_limit << \"'.\";\n exit(1);\n }\n \/\/ 0 indicates no limit or not set\n if (bytes_limit == 0) {\n default_pool_mem_limit_ = -1;\n } else {\n default_pool_mem_limit_ = bytes_limit;\n }\n return;\n }\n default_pool_only_ = false;\n\n jmethodID start_id; \/\/ RequestPoolService.start(), only called in this method.\n JniMethodDescriptor methods[] = {\n {\"\", \"(Ljava\/lang\/String;Ljava\/lang\/String;)V\", &ctor_},\n {\"start\", \"()V\", &start_id},\n {\"resolveRequestPool\", \"([B)[B\", &resolve_request_pool_id_},\n {\"getPoolConfig\", \"([B)[B\", &get_pool_config_id_}};\n\n JNIEnv* jni_env = getJNIEnv();\n request_pool_service_class_ =\n jni_env->FindClass(\"com\/cloudera\/impala\/util\/RequestPoolService\");\n EXIT_IF_EXC(jni_env);\n uint32_t num_methods = sizeof(methods) \/ sizeof(methods[0]);\n for (int i = 0; i < num_methods; ++i) {\n EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,\n &(methods[i])));\n }\n\n jstring fair_scheduler_config_path =\n jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());\n EXIT_IF_EXC(jni_env);\n jstring llama_site_path =\n jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());\n EXIT_IF_EXC(jni_env);\n\n jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,\n fair_scheduler_config_path, llama_site_path);\n EXIT_IF_EXC(jni_env);\n EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,\n &request_pool_service_));\n jni_env->CallObjectMethod(request_pool_service_, start_id);\n EXIT_IF_EXC(jni_env);\n}\n\nStatus RequestPoolService::ResolveRequestPool(const string& requested_pool_name,\n const string& user, TResolveRequestPoolResult* resolved_pool) {\n if (default_pool_only_) {\n resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);\n resolved_pool->__set_has_access(true);\n return Status::OK;\n }\n\n TResolveRequestPoolParams params;\n params.__set_user(user);\n params.__set_requested_pool(requested_pool_name);\n return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,\n resolved_pool);\n}\n\nStatus RequestPoolService::GetPoolConfig(const string& pool_name,\n TPoolConfigResult* pool_config) {\n if (default_pool_only_) {\n pool_config->__set_max_requests(\n FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);\n pool_config->__set_mem_limit(\n FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);\n pool_config->__set_max_queued(FLAGS_default_pool_max_queued);\n return Status::OK;\n }\n\n TPoolConfigParams params;\n params.__set_pool(pool_name);\n RETURN_IF_ERROR(JniUtil::CallJniMethod(\n request_pool_service_, get_pool_config_id_, params, pool_config));\n if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);\n if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);\n return Status::OK;\n}\nAdmission controller: Change default values for the \"default pool\"\/\/ Copyright 2014 Cloudera Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain 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#include \"scheduling\/request-pool-service.h\"\n\n#include \n#include \n\n#include \"common\/logging.h\"\n#include \"rpc\/thrift-util.h\"\n#include \"util\/jni-util.h\"\n#include \"util\/parse-util.h\"\n\nusing namespace std;\nusing namespace impala;\n\nDEFINE_string(fair_scheduler_allocation_path, \"\", \"Path to the fair scheduler \"\n \"allocation file (fair-scheduler.xml).\");\nDEFINE_string(llama_site_path, \"\", \"Path to the Llama configuration file \"\n \"(llama-site.xml). If set, fair_scheduler_allocation_path must also be set.\");\n\n\/\/ The default_pool parameters are used if fair scheduler allocation and Llama\n\/\/ configuration files are not provided. The default values for this 'default pool'\n\/\/ are the same as the default values for pools defined via the fair scheduler\n\/\/ allocation file and Llama configurations.\nDEFINE_int64(default_pool_max_requests, 20, \"Maximum number of concurrent outstanding \"\n \"requests allowed to run before queueing incoming requests. A negative value \"\n \"indicates no limit. 0 indicates no requests will be admitted. Ignored if \"\n \"fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_string(default_pool_mem_limit, \"\", \"Maximum amount of memory that all \"\n \"outstanding requests in this pool may use before new requests to this pool\"\n \" are queued. Specified as a number of bytes ('[bB]?'), megabytes \"\n \"('[mM]'), gigabytes ('[gG]'), or percentage of the physical memory \"\n \"('%'). 0 or not setting indicates no limit. Defaults to bytes if no unit is \"\n \"given. Ignored if fair_scheduler_config_path and llama_site_path are set.\");\nDEFINE_int64(default_pool_max_queued, 50, \"Maximum number of requests allowed to be \"\n \"queued before rejecting requests. A negative value or 0 indicates requests \"\n \"will always be rejected once the maximum number of concurrent requests are \"\n \"executing. Ignored if fair_scheduler_config_path and \"\n \"llama_site_path are set.\");\n\n\/\/ Flags to disable the pool limits for all pools.\nDEFINE_bool(disable_pool_mem_limits, false, \"Disables all per-pool mem limits.\");\nDEFINE_bool(disable_pool_max_requests, false, \"Disables all per-pool limits on the \"\n \"maximum number of running requests.\");\n\nDECLARE_bool(enable_rm);\n\n\/\/ Pool name used when the configuration files are not specified.\nconst string DEFAULT_POOL_NAME = \"default-pool\";\n\nRequestPoolService::RequestPoolService() {\n if (FLAGS_fair_scheduler_allocation_path.empty() &&\n FLAGS_llama_site_path.empty()) {\n if (FLAGS_enable_rm) {\n LOG(ERROR) << \"If resource management is enabled, -fair_scheduler_allocation_path \"\n << \"is required.\";\n exit(1);\n }\n default_pool_only_ = true;\n bool is_percent; \/\/ not used\n int64_t bytes_limit = ParseUtil::ParseMemSpec(FLAGS_default_pool_mem_limit,\n &is_percent);\n \/\/ -1 indicates an error occurred\n if (bytes_limit < 0) {\n LOG(ERROR) << \"Unable to parse default pool mem limit from '\"\n << FLAGS_default_pool_mem_limit << \"'.\";\n exit(1);\n }\n \/\/ 0 indicates no limit or not set\n if (bytes_limit == 0) {\n default_pool_mem_limit_ = -1;\n } else {\n default_pool_mem_limit_ = bytes_limit;\n }\n return;\n }\n default_pool_only_ = false;\n\n jmethodID start_id; \/\/ RequestPoolService.start(), only called in this method.\n JniMethodDescriptor methods[] = {\n {\"\", \"(Ljava\/lang\/String;Ljava\/lang\/String;)V\", &ctor_},\n {\"start\", \"()V\", &start_id},\n {\"resolveRequestPool\", \"([B)[B\", &resolve_request_pool_id_},\n {\"getPoolConfig\", \"([B)[B\", &get_pool_config_id_}};\n\n JNIEnv* jni_env = getJNIEnv();\n request_pool_service_class_ =\n jni_env->FindClass(\"com\/cloudera\/impala\/util\/RequestPoolService\");\n EXIT_IF_EXC(jni_env);\n uint32_t num_methods = sizeof(methods) \/ sizeof(methods[0]);\n for (int i = 0; i < num_methods; ++i) {\n EXIT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, request_pool_service_class_,\n &(methods[i])));\n }\n\n jstring fair_scheduler_config_path =\n jni_env->NewStringUTF(FLAGS_fair_scheduler_allocation_path.c_str());\n EXIT_IF_EXC(jni_env);\n jstring llama_site_path =\n jni_env->NewStringUTF(FLAGS_llama_site_path.c_str());\n EXIT_IF_EXC(jni_env);\n\n jobject request_pool_service = jni_env->NewObject(request_pool_service_class_, ctor_,\n fair_scheduler_config_path, llama_site_path);\n EXIT_IF_EXC(jni_env);\n EXIT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, request_pool_service,\n &request_pool_service_));\n jni_env->CallObjectMethod(request_pool_service_, start_id);\n EXIT_IF_EXC(jni_env);\n}\n\nStatus RequestPoolService::ResolveRequestPool(const string& requested_pool_name,\n const string& user, TResolveRequestPoolResult* resolved_pool) {\n if (default_pool_only_) {\n resolved_pool->__set_resolved_pool(DEFAULT_POOL_NAME);\n resolved_pool->__set_has_access(true);\n return Status::OK;\n }\n\n TResolveRequestPoolParams params;\n params.__set_user(user);\n params.__set_requested_pool(requested_pool_name);\n return JniUtil::CallJniMethod(request_pool_service_, resolve_request_pool_id_, params,\n resolved_pool);\n}\n\nStatus RequestPoolService::GetPoolConfig(const string& pool_name,\n TPoolConfigResult* pool_config) {\n if (default_pool_only_) {\n pool_config->__set_max_requests(\n FLAGS_disable_pool_max_requests ? -1 : FLAGS_default_pool_max_requests);\n pool_config->__set_mem_limit(\n FLAGS_disable_pool_mem_limits ? -1 : default_pool_mem_limit_);\n pool_config->__set_max_queued(FLAGS_default_pool_max_queued);\n return Status::OK;\n }\n\n TPoolConfigParams params;\n params.__set_pool(pool_name);\n RETURN_IF_ERROR(JniUtil::CallJniMethod(\n request_pool_service_, get_pool_config_id_, params, pool_config));\n if (FLAGS_disable_pool_max_requests) pool_config->__set_max_requests(-1);\n if (FLAGS_disable_pool_mem_limits) pool_config->__set_mem_limit(-1);\n return Status::OK;\n}\n<|endoftext|>"} {"text":"#include \"stochastic_trainer.h\"\n#include \"common\/timer.h\"\n#include \"common\/logger.h\"\n#include \"common\/math.hpp\"\n#include \"common\/thread_pool.h\"\n#include \"common\/random.hpp\"\n#include \"common\/log_search.hpp\"\n#include \"sampler.h\"\n#include \"accumulator.h\"\n\nnamespace ncv\n{\n namespace detail\n {\n \/\/\/\n \/\/\/ \\brief tune the regularization factor for a given criterion (if needed)\n \/\/\/\n template\n <\n typename toperator\n >\n static trainer_result_t tune(const toperator& op, const string_t& criterion)\n {\n if (accumulator_t::can_regularize(criterion))\n {\n return log_min_search(op, -1.0, +6.0, 0.2);\n }\n\n else\n {\n return op(0.0);\n }\n }\n\n struct rnd_t\n {\n rnd_t(random_t& gen)\n : m_gen(gen)\n {\n }\n\n size_t operator()(size_t i)\n {\n return m_gen() % i;\n }\n\n random_t& m_gen;\n };\n\n static void stochastic_train(\n trainer_data_t& data,\n stochastic_optimizer type, size_t epochs, scalar_t alpha0, scalar_t beta,\n trainer_result_t& result, thread_pool_t::mutex_t& mutex)\n {\n samples_t tsamples = data.m_tsampler.get();\n samples_t vsamples = data.m_vsampler.get();\n\n random_t xrng(0, tsamples.size());\n rnd_t xrnd(xrng);\n\n timer_t timer;\n\n vector_t x = data.m_x0, xparam = x, xavg = x;\n\n vector_t gavg(x.size());\n gavg.setZero();\n\n scalar_t alpha = alpha0;\n scalar_t sumb = 1.0 \/ alpha;\n\n for (size_t e = 0; e < epochs; e ++)\n {\n std::random_shuffle(tsamples.begin(), tsamples.end(), xrnd);\n\n \/\/ one epoch: a pass through all training samples\n switch (type)\n {\n \/\/ stochastic gradient\n case stochastic_optimizer::SG:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n x.noalias() -= alpha * data.m_gacc.vgrad();\n }\n xparam = x;\n break;\n\n \/\/ stochastic gradient average\n case stochastic_optimizer::SGA:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n const vector_t g = data.m_gacc.vgrad();\n\n const scalar_t b = 1.0 \/ alpha;\n gavg = (gavg * sumb + g * b) \/ (sumb + b);\n sumb = sumb + b;\n\n x.noalias() -= alpha * gavg;\n }\n xparam = x;\n break;\n\n \/\/ stochastic iterative average\n case stochastic_optimizer::SIA:\n default:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n x.noalias() -= alpha * data.m_gacc.vgrad();\n\n const scalar_t b = 1.0 \/ alpha;\n xavg = (xavg * sumb + x * b) \/ (sumb + b);\n sumb = sumb + b;\n }\n xparam = xavg;\n break;\n }\n\n \/\/ evaluate training samples\n data.m_lacc.reset(xparam);\n data.m_lacc.update(data.m_task, tsamples, data.m_loss);\n const scalar_t tvalue = data.m_lacc.value();\n const scalar_t terror = data.m_lacc.error();\n\n \/\/ evaluate validation samples\n data.m_lacc.reset(xparam);\n data.m_lacc.update(data.m_task, vsamples, data.m_loss);\n const scalar_t vvalue = data.m_lacc.value();\n const scalar_t verror = data.m_lacc.error();\n\n \/\/ OK, update the optimum solution\n const thread_pool_t::lock_t lock(mutex);\n\n result.update(xparam, tvalue, terror, vvalue, verror, e,\n scalars_t({ alpha0, data.m_lacc.lambda() }));\n\n log_info()\n << \"[train = \" << tvalue << \"\/\" << terror\n << \", valid = \" << vvalue << \"\/\" << verror\n << \", rate = \" << alpha << \"\/\" << alpha0\n << \", epoch = \" << e << \"\/\" << epochs\n << \", dims = \" << data.m_lacc.psize()\n << \", lambda = \" << data.m_lacc.lambda()\n << \"] done in \" << timer.elapsed() << \".\";\n }\n }\n }\n\n trainer_result_t stochastic_train(\n const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,\n const loss_t& loss, const string_t& criterion,\n stochastic_optimizer optimizer, size_t epochs)\n {\n const auto op = [&] (scalar_t lambda)\n {\n \/\/ prepare workers\n thread_pool_t wpool(nthreads);\n thread_pool_t::mutex_t mutex;\n\n const size_t iterations = epochs * tsampler.size(); \/\/ SGD iterations\n const scalar_t beta = std::pow(0.01, 1.0 \/ iterations); \/\/ Learning rate decay rate\n\n vector_t x0;\n model.save_params(x0);\n\n trainer_result_t result;\n\n \/\/ tune the learning rate\n const scalars_t alphas = { 0.001, 0.010, 0.100 };\n for (scalar_t alpha : alphas)\n {\n wpool.enqueue([=, &task, &loss, &model, &x0, &result, &mutex]()\n {\n accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);\n accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);\n\n trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);\n\n detail::stochastic_train(data, optimizer, epochs, alpha, beta, result, mutex);\n });\n }\n\n wpool.wait();\n\n \/\/ OK\n return result;\n };\n\n \/\/ tune the regularization factor (if needed)\n return detail::tune(op, criterion);\n }\n\n stochastic_trainer_t::stochastic_trainer_t(const string_t& parameters)\n : trainer_t(parameters,\n \"parameters: opt=sg[,sga,sia],epoch=16[1,1024]\")\n {\n }\n\n trainer_result_t stochastic_trainer_t::train(\n const task_t& task, const fold_t& fold, const loss_t& loss, size_t nthreads, const string_t& criterion,\n model_t& model) const\n {\n if (fold.second != protocol::train)\n {\n log_error() << \"stochastic trainer: can only train models with training samples!\";\n return trainer_result_t();\n }\n\n \/\/ initialize the model\n model.resize(task, true);\n model.random_params();\n\n \/\/ prune training & validation data\n sampler_t tsampler(task);\n tsampler.setup(fold).setup(sampler_t::atype::annotated);\n\n sampler_t vsampler(task);\n tsampler.split(90, vsampler);\n\n if (tsampler.empty() || vsampler.empty())\n {\n log_error() << \"stochastic trainer: no annotated training samples!\";\n return trainer_result_t();\n }\n\n \/\/ parameters\n const size_t epochs = math::clamp(text::from_params(configuration(), \"epoch\", 16), 1, 1024);\n\n const stochastic_optimizer optimizer = text::from_string\n (text::from_params(configuration(), \"opt\", \"sg\"));\n\n \/\/ train the model\n const trainer_result_t result = ncv::stochastic_train(\n model, task, tsampler, vsampler, nthreads,\n loss, criterion, optimizer, epochs);\n\n log_info() << \"optimum [train = \" << result.m_opt_state.m_tvalue << \"\/\" << result.m_opt_state.m_terror\n << \", valid = \" << result.m_opt_state.m_vvalue << \"\/\" << result.m_opt_state.m_verror\n << \", epoch = \" << result.m_opt_epoch\n << \", config = \" << text::concatenate(result.m_opt_config, \"\/\")\n << \"].\";\n\n \/\/ OK\n if (result.valid())\n {\n model.load_params(result.m_opt_params);\n }\n return result;\n }\n}\nmore efficient tuning of the learning rate for stochastic trainer#include \"stochastic_trainer.h\"\n#include \"common\/timer.h\"\n#include \"common\/logger.h\"\n#include \"common\/math.hpp\"\n#include \"common\/thread_pool.h\"\n#include \"common\/random.hpp\"\n#include \"common\/log_search.hpp\"\n#include \"sampler.h\"\n#include \"accumulator.h\"\n\nnamespace ncv\n{\n namespace detail\n {\n \/\/\/\n \/\/\/ \\brief tune the regularization factor for a given criterion (if needed)\n \/\/\/\n template\n <\n typename toperator\n >\n static trainer_result_t tune(const toperator& op, const string_t& criterion)\n {\n if (accumulator_t::can_regularize(criterion))\n {\n return log_min_search(op, -1.0, +6.0, 0.2);\n }\n\n else\n {\n return op(0.0);\n }\n }\n\n struct rnd_t\n {\n rnd_t(random_t& gen)\n : m_gen(gen)\n {\n }\n\n size_t operator()(size_t i)\n {\n return m_gen() % i;\n }\n\n random_t& m_gen;\n };\n\n static void stochastic_train(\n trainer_data_t& data,\n stochastic_optimizer type, size_t epochs, scalar_t alpha0, scalar_t beta,\n trainer_result_t& result, thread_pool_t::mutex_t& mutex)\n {\n samples_t tsamples = data.m_tsampler.get();\n samples_t vsamples = data.m_vsampler.get();\n\n random_t xrng(0, tsamples.size());\n rnd_t xrnd(xrng);\n\n timer_t timer;\n\n vector_t x = data.m_x0, xparam = x, xavg = x;\n\n vector_t gavg(x.size());\n gavg.setZero();\n\n scalar_t alpha = alpha0;\n scalar_t sumb = 1.0 \/ alpha;\n\n for (size_t e = 0; e < epochs; e ++)\n {\n std::random_shuffle(tsamples.begin(), tsamples.end(), xrnd);\n\n \/\/ one epoch: a pass through all training samples\n switch (type)\n {\n \/\/ stochastic gradient\n case stochastic_optimizer::SG:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n x.noalias() -= alpha * data.m_gacc.vgrad();\n }\n xparam = x;\n break;\n\n \/\/ stochastic gradient average\n case stochastic_optimizer::SGA:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n const vector_t g = data.m_gacc.vgrad();\n\n const scalar_t b = 1.0 \/ alpha;\n gavg = (gavg * sumb + g * b) \/ (sumb + b);\n sumb = sumb + b;\n\n x.noalias() -= alpha * gavg;\n }\n xparam = x;\n break;\n\n \/\/ stochastic iterative average\n case stochastic_optimizer::SIA:\n default:\n for (size_t i = 0; i < tsamples.size(); i ++, alpha *= beta)\n {\n data.m_gacc.reset(x);\n data.m_gacc.update(data.m_task, tsamples[i], data.m_loss);\n\n x.noalias() -= alpha * data.m_gacc.vgrad();\n\n const scalar_t b = 1.0 \/ alpha;\n xavg = (xavg * sumb + x * b) \/ (sumb + b);\n sumb = sumb + b;\n }\n xparam = xavg;\n break;\n }\n\n \/\/ evaluate training samples\n data.m_lacc.reset(xparam);\n data.m_lacc.update(data.m_task, tsamples, data.m_loss);\n const scalar_t tvalue = data.m_lacc.value();\n const scalar_t terror = data.m_lacc.error();\n\n \/\/ evaluate validation samples\n data.m_lacc.reset(xparam);\n data.m_lacc.update(data.m_task, vsamples, data.m_loss);\n const scalar_t vvalue = data.m_lacc.value();\n const scalar_t verror = data.m_lacc.error();\n\n \/\/ OK, update the optimum solution\n const thread_pool_t::lock_t lock(mutex);\n\n result.update(xparam, tvalue, terror, vvalue, verror, e,\n scalars_t({ alpha0, data.m_lacc.lambda() }));\n\n log_info()\n << \"[train = \" << tvalue << \"\/\" << terror\n << \", valid = \" << vvalue << \"\/\" << verror\n << \", rate = \" << alpha << \"\/\" << alpha0\n << \", epoch = \" << e << \"\/\" << epochs\n << \", dims = \" << data.m_lacc.psize()\n << \", lambda = \" << data.m_lacc.lambda()\n << \"] done in \" << timer.elapsed() << \".\";\n }\n }\n }\n\n trainer_result_t stochastic_train(\n const model_t& model, const task_t& task, const sampler_t& tsampler, const sampler_t& vsampler, size_t nthreads,\n const loss_t& loss, const string_t& criterion,\n stochastic_optimizer optimizer, size_t epochs)\n {\n const auto op = [&] (scalar_t lambda)\n {\n const size_t iterations = epochs * tsampler.size(); \/\/ SGD iterations\n const scalar_t beta = std::pow(0.01, 1.0 \/ iterations); \/\/ Learning rate decay rate\n \n const scalar_t min_log_alpha = -3;\n const scalar_t max_log_alpha = +0;\n const scalar_t dif_log_alpha = (max_log_alpha - min_log_alpha) \/ std::min(size_t(8), nthreads);\n \n scalars_t alphas;\n for (scalar_t log_alpha = min_log_alpha; log_alpha < max_log_alpha + 1e-6; log_alpha += dif_log_alpha)\n {\n alphas.push_back(std::exp(log_alpha));\n }\n\n \/\/ tune the learning rate (single epoch)\n vector_t x0;\n model.save_params(x0);\n \n thread_pool_t wpool(nthreads);\n thread_pool_t::mutex_t mutex;\n \n trainer_result_t result;\n for (scalar_t alpha : alphas)\n {\n wpool.enqueue([=, &task, &loss, &model, &x0, &result, &mutex]()\n {\n accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);\n accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);\n\n trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);\n\n detail::stochastic_train(data, optimizer, 1, alpha, beta, result, mutex);\n });\n }\n\n wpool.wait();\n \n \/\/ train with the optimum learning rate (multiple epochs)\n const scalar_t opt_alpha = result.m_opt_config[0];\n log_info() << \"optimum learning rate = \" << opt_alpha << \".\";\n \n result = trainer_result_t();\n \n accumulator_t lacc(model, 1, criterion, criterion_t::type::value, lambda);\n accumulator_t gacc(model, 1, criterion, criterion_t::type::vgrad, lambda);\n \n trainer_data_t data(task, tsampler, vsampler, loss, x0, lacc, gacc);\n \n detail::stochastic_train(data, optimizer, epochs, opt_alpha, beta, result, mutex);\n\n \/\/ OK\n return result;\n };\n\n \/\/ tune the regularization factor (if needed)\n return detail::tune(op, criterion);\n }\n\n stochastic_trainer_t::stochastic_trainer_t(const string_t& parameters)\n : trainer_t(parameters,\n \"parameters: opt=sg[,sga,sia],epoch=16[1,1024]\")\n {\n }\n\n trainer_result_t stochastic_trainer_t::train(\n const task_t& task, const fold_t& fold, const loss_t& loss, size_t nthreads, const string_t& criterion,\n model_t& model) const\n {\n if (fold.second != protocol::train)\n {\n log_error() << \"stochastic trainer: can only train models with training samples!\";\n return trainer_result_t();\n }\n\n \/\/ initialize the model\n model.resize(task, true);\n model.random_params();\n\n \/\/ prune training & validation data\n sampler_t tsampler(task);\n tsampler.setup(fold).setup(sampler_t::atype::annotated);\n\n sampler_t vsampler(task);\n tsampler.split(90, vsampler);\n\n if (tsampler.empty() || vsampler.empty())\n {\n log_error() << \"stochastic trainer: no annotated training samples!\";\n return trainer_result_t();\n }\n\n \/\/ parameters\n const size_t epochs = math::clamp(text::from_params(configuration(), \"epoch\", 16), 1, 1024);\n\n const stochastic_optimizer optimizer = text::from_string\n (text::from_params(configuration(), \"opt\", \"sg\"));\n\n \/\/ train the model\n const trainer_result_t result = ncv::stochastic_train(\n model, task, tsampler, vsampler, nthreads,\n loss, criterion, optimizer, epochs);\n\n log_info() << \"optimum [train = \" << result.m_opt_state.m_tvalue << \"\/\" << result.m_opt_state.m_terror\n << \", valid = \" << result.m_opt_state.m_vvalue << \"\/\" << result.m_opt_state.m_verror\n << \", epoch = \" << result.m_opt_epoch\n << \", config = \" << text::concatenate(result.m_opt_config, \"\/\")\n << \"].\";\n\n \/\/ OK\n if (result.valid())\n {\n model.load_params(result.m_opt_params);\n }\n return result;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/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#include \"pyiree\/rt\/status_utils.h\"\n\n#include \"absl\/strings\/str_cat.h\"\n\nnamespace iree {\nnamespace python {\n\nnamespace {\n\nPyObject* ApiStatusToPyExcClass(iree_status_t status) {\n switch (iree_status_code(status)) {\n case IREE_STATUS_INVALID_ARGUMENT:\n return PyExc_ValueError;\n case IREE_STATUS_OUT_OF_RANGE:\n return PyExc_IndexError;\n case IREE_STATUS_UNIMPLEMENTED:\n return PyExc_NotImplementedError;\n default:\n return PyExc_RuntimeError;\n }\n}\n\n} \/\/ namespace\n\npybind11::error_already_set ApiStatusToPyExc(iree_status_t status,\n const char* message) {\n assert(!iree_status_is_ok(status));\n auto full_message = absl::StrCat(\n message, \": \", iree_status_code_string(iree_status_code(status)));\n PyErr_SetString(ApiStatusToPyExcClass(status), full_message.c_str());\n iree_status_ignore(status);\n return pybind11::error_already_set();\n}\n\npybind11::error_already_set RaisePyError(PyObject* exc_class,\n const char* message) {\n PyErr_SetString(exc_class, message);\n return pybind11::error_already_set();\n}\n\n} \/\/ namespace python\n} \/\/ namespace iree\nPython error messages print the full IREE status if available.\/\/ Copyright 2019 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/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#include \"pyiree\/rt\/status_utils.h\"\n\n#include \"absl\/strings\/str_cat.h\"\n\nnamespace iree {\nnamespace python {\n\nnamespace {\n\nPyObject* ApiStatusToPyExcClass(iree_status_t status) {\n switch (iree_status_code(status)) {\n case IREE_STATUS_INVALID_ARGUMENT:\n return PyExc_ValueError;\n case IREE_STATUS_OUT_OF_RANGE:\n return PyExc_IndexError;\n case IREE_STATUS_UNIMPLEMENTED:\n return PyExc_NotImplementedError;\n default:\n return PyExc_RuntimeError;\n }\n}\n\n} \/\/ namespace\n\npybind11::error_already_set ApiStatusToPyExc(iree_status_t status,\n const char* message) {\n assert(!iree_status_is_ok(status));\n std::string full_message;\n\n char* iree_message;\n size_t iree_message_length;\n if (iree_status_to_string(status, &iree_message, &iree_message_length)) {\n full_message = absl::StrCat(\n message, \": \", absl::string_view(iree_message, iree_message_length));\n iree_allocator_free(iree_allocator_system(), iree_message);\n } else {\n full_message = absl::StrCat(\n message, \": \", iree_status_code_string(iree_status_code(status)));\n }\n\n PyErr_SetString(ApiStatusToPyExcClass(status), full_message.c_str());\n iree_status_ignore(status);\n return pybind11::error_already_set();\n}\n\npybind11::error_already_set RaisePyError(PyObject* exc_class,\n const char* message) {\n PyErr_SetString(exc_class, message);\n return pybind11::error_already_set();\n}\n\n} \/\/ namespace python\n} \/\/ namespace iree\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; indent-tabs-mode: nil -*- *\/\n#include \"_python.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"callback_stream.h\"\n#include \"exception.h\"\n#include \"pystream.h\"\n#include \"seq_stream.h\"\n#include \"text_stream.h\"\n\nnamespace io = schwa::io;\nnamespace tok = schwa::tokenizer;\n\nusing schwa::to_underlying;\n\n\n\/\/ ============================================================================\n\/\/ Module-level objects\n\/\/ ============================================================================\nstatic PyObject *module_TokenError = nullptr;\n\n\n\/\/ ============================================================================\n\/\/ PyTokenizer\n\/\/ ============================================================================\ntypedef struct {\n PyObject_HEAD\n tok::Tokenizer *tokenizer;\n} PyTokenizer;\n\n\nstatic PyObject *\nPyTokenizer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {\n PyTokenizer *self = (PyTokenizer *)type->tp_alloc(type, 0);\n if (self != nullptr)\n self->tokenizer = new tok::Tokenizer();\n return (PyObject *)self;\n}\n\n\nstatic void\nPyTokenizer_dealloc(PyTokenizer *self) {\n PyObject *const pyself = (PyObject *)self;\n delete self->tokenizer;\n pyself->ob_type->tp_free(pyself);\n}\n\n\nstatic const char *const PyTokenizer_tokenize__doc =\n \"Identifies paragraph, sentence and token boundaries in (English) text or HTML,\\n\"\n \"using a rule-based lexer.\\n\"\n \"\\n\"\n \"Arguments:\\n\"\n \"\\n\"\n \" source: a UTF-8 byte string\\n\"\n \"\\n\"\n \" dest: the output method, one of the following Python types:\\n\"\n \" - str (default): outputs a UTF-8 string with '\\\\n\\\\n', '\\\\n' and ' ' as\\n\"\n \" paragraph, sentence and token delimiters respectively\\n\"\n \" - unicode: like str, but with UTF-8 decoded\\n\"\n \" - list: outputs a list of paragraphs, each containing a list of sentences,\\n\"\n \" each containing a list of (offset, raw_token, [normalised_token]) tuples\\n\"\n \" or:\\n\"\n \" - any other callable: makes callbacks with arguments\\n\"\n \" (emit_type, offset, raw, norm)\\n\"\n \" - any other object: calls methods named according to emit_type when present\\n\"\n \"\\n\"\n \" Offset is a byte offset into the input string.\\n\"\n \" Emit types are:\\n\"\n \" begin_{document,paragraph,sentence,heading,list,item},\\n\"\n \" end_{document,paragraph,sentence,heading,list,item},\\n\"\n \" token and error\\n\"\n \"\\n\"\n \" filename: the path to a file to use instead of source\\n\"\n \"\\n\"\n \" buffer_size: \\n\"\n \"\\n\"\n \" errors: a method for dealing with bad byte sequences, may be one of:\\n\"\n \" - ERROR_SKIP (default): ignores errors\\n\"\n \" - ERROR_CALL: emits ('error', offset, bytes)\\n\"\n \" - ERROR_THROW: throws a TokenError\\n\"\n \"\\n\"\n \" normalise: a boolean (default True) indicating whether to perform\\n\"\n \" normalisation on the output (such as directed quotes, all dashes as --, and\\n\"\n \" * to indicate list items). Only applies when dest is str or unicode.\\n\"\n \"\\n\"\n \" mmap: a boolean (default False) indicating whether to process the file\\n\"\n \" memory-mapped, when the filename argument is used.\";\n\nPyObject *\nPyTokenizer_tokenize(PyTokenizer *self, PyObject *args, PyObject *kwargs) {\n \/\/ Setup default values for kwarg parsing.\n PyObject *pysrc = nullptr;\n PyObject *pydest = (PyObject *)&SCHWA_PY_BYTES_TYPE;\n const char *filename = nullptr;\n Py_ssize_t buffer_size = static_cast(tok::DEFAULT_BUFFER_SIZE);\n int pyerrors = to_underlying(tok::OnError::SKIP);\n int normalise = 1;\n int use_mmap = 0;\n\n \/\/ Parse the kwargs.\n static const char *kwlist[] = {\"source\", \"dest\", \"filename\", \"buffer_size\", \"errors\", \"normalise\", \"mmap\", 0};\n if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OOsniii:tokenize\", (char **)kwlist, &pysrc, &pydest, &filename, &buffer_size, &pyerrors, &normalise, &use_mmap))\n return 0;\n\n \/\/ Validate the arguments.\n if (!pysrc && !filename)\n return PyErr_Format(PyExc_TypeError, \"tokenize() requires either a source or filename argument\");\n if (pysrc) {\n if (PyUnicode_Check(pysrc))\n return PyErr_Format(PyExc_TypeError, \"tokenize() does not accept unicode objects, use unicode.encode('utf-8')\");\n else if (!SCHWA_PY_CHECK_BUFFER(pysrc))\n return PyErr_Format(PyExc_TypeError, \"tokenize() source must support the buffer interface\");\n }\n if (buffer_size <= 0)\n return PyErr_Format(PyExc_ValueError, \"tokenize() buffer_size must be positive, %zu given\", buffer_size);\n tok::OnError onerror = tok::OnError::SKIP;\n switch (pyerrors) {\n case to_underlying(tok::OnError::CALL):\n onerror = tok::OnError::CALL;\n break;\n case to_underlying(tok::OnError::SKIP):\n onerror = tok::OnError::SKIP;\n break;\n case to_underlying(tok::OnError::THROW):\n onerror = tok::OnError::THROW;\n break;\n default:\n return PyErr_Format(PyExc_ValueError, \"tokenize() unknown bad byte error handler, %d given\", pyerrors);\n }\n\n try {\n \/\/ Work out what the destination for the tokenizers output should be.\n std::unique_ptr stream;\n if ((void *)pydest == (void *)&SCHWA_PY_BYTES_TYPE)\n stream.reset(new tok::PyBytesStream(normalise));\n else if ((void *)pydest == (void *)&PyUnicode_Type)\n stream.reset(new tok::PyUnicodeStream(normalise));\n else if ((void *)pydest == (void *)&PyList_Type)\n stream.reset(new tok::PyListStream());\n else if ((void *)pydest == (void *)&PyTuple_Type)\n stream.reset(new tok::PyTupleStream());\n else if (PyCallable_Check(pydest))\n stream.reset(new tok::PyCallFuncStream(pydest));\n else\n stream.reset(new tok::PyCallObjectStream(pydest));\n\n \/\/ Call the appropriate tokenize method on the Tokenizer object.\n if (filename) {\n if (use_mmap)\n self->tokenizer->tokenize_mmap(*stream, filename, onerror);\n else {\n std::ifstream in(filename);\n if (!in)\n return PyErr_Format(PyExc_IOError, \"tokenize() could not open file '%s' for reading\", filename);\n self->tokenizer->tokenize_stream(*stream, in, static_cast(buffer_size), onerror);\n }\n }\n else {\n \/\/ Obtain the underlying buffer and pass it to the tokenizer, ensuring we release it.\n Py_buffer buffer;\n if (PyObject_GetBuffer(pysrc, &buffer, PyBUF_SIMPLE) != 0)\n return PyErr_Format(PyExc_ValueError, \"tokenize() only supports simple buffer objects\");\n if (buffer.len < 0)\n return PyErr_Format(PyExc_ValueError, \"Size of the provided source's underlying buffer is negative\");\n try {\n self->tokenizer->tokenize(*stream, (char *)buffer.buf, static_cast(buffer.len), onerror);\n }\n catch (...) {\n PyBuffer_Release(&buffer);\n throw;\n }\n }\n\n \/\/ Return what the stream defines is the return value for this function.\n return stream->return_value();\n }\n catch (tok::TokenError &e) {\n PyErr_SetString(module_TokenError, e.what());\n return nullptr;\n }\n catch (tok::PyRaise &e) {\n return nullptr;\n }\n catch (schwa::IOException &e) {\n PyErr_SetString(PyExc_IOError, e.what());\n return nullptr;\n }\n}\n\n\nstatic PyMethodDef PyTokenizer_methods[] = {\n {\"tokenize\", (PyCFunction)PyTokenizer_tokenize, METH_VARARGS | METH_KEYWORDS, PyTokenizer_tokenize__doc},\n {nullptr} \/* Sentinel *\/\n};\n\n\nstatic PyTypeObject PyTokenizerType = {\n PyVarObject_HEAD_INIT(nullptr, 0)\n \"tokenizer.Tokenizer\", \/* tp_name *\/\n sizeof(PyTokenizer), \/* tp_basicsize *\/\n 0, \/* tp_itemsize *\/\n (destructor)PyTokenizer_dealloc, \/* tp_dealloc *\/\n 0, \/* tp_print *\/\n 0, \/* tp_getattr *\/\n 0, \/* tp_setattr *\/\n 0, \/* tp_compare *\/\n 0, \/* tp_repr *\/\n 0, \/* tp_as_number *\/\n 0, \/* tp_as_sequence *\/\n 0, \/* tp_as_mapping *\/\n 0, \/* tp_hash *\/\n 0, \/* tp_call *\/\n 0, \/* tp_str *\/\n 0, \/* tp_getattro *\/\n 0, \/* tp_setattro *\/\n 0, \/* tp_as_buffer *\/\n Py_TPFLAGS_DEFAULT, \/* tp_flags *\/\n \"Wrapper around the C++ Tokenizer class.\", \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n PyTokenizer_methods, \/* tp_methods *\/\n 0, \/* tp_members *\/\n 0, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n (initproc)0, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n PyTokenizer_new, \/* tp_new *\/\n};\n\n\n\/\/ ============================================================================\n\/\/ Module\n\/\/ ============================================================================\nstatic const char *const module_name = \"tokenizer\";\nstatic const char *const module_doc = \"Schwa Lab tokenizer module\";\n\nstatic PyMethodDef module_methods[] = {\n {nullptr} \/* Sentinel *\/\n};\n\n#ifdef IS_PY3K\nstatic PyModuleDef module_def = {\n PyModuleDef_HEAD_INIT, \/* m_base *\/\n module_name, \/* m_name *\/\n module_doc, \/* m_doc *\/\n 0, \/* m_size *\/\n module_methods, \/* m_methods *\/\n nullptr, \/* m_reload *\/\n nullptr, \/* m_traverse *\/\n nullptr, \/* m_clear *\/\n nullptr, \/* m_free *\/\n};\n#endif\n\n\nstatic PyObject *\n_inittokenizer(void) {\n \/\/ Ensure that PyTokenizerType is ready for use.\n if (PyType_Ready(&PyTokenizerType) != 0)\n return nullptr;\n\n \/\/ Construct the module.\n#ifdef IS_PY3K\n PyObject *const m = PyModule_Create(&module_def);\n#else\n PyObject *const m = Py_InitModule3(module_name, module_methods, module_doc);\n#endif\n if (m == nullptr)\n return nullptr;\n\n \/\/ Add PyTokenizerType to the module.\n Py_INCREF(&PyTokenizerType);\n if (PyModule_AddObject(m, \"Tokenizer\", (PyObject *)&PyTokenizerType) != 0)\n return nullptr;\n\n \/\/ Create the TokenError exception and add it to the module.\n module_TokenError = PyErr_NewException((char *)\"tokenizer.TokenError\", nullptr, nullptr);\n if (module_TokenError == nullptr)\n return nullptr;\n Py_INCREF(&module_TokenError);\n if (PyModule_AddObject(m, \"TokenError\", module_TokenError) != 0)\n return nullptr;\n\n \/\/ Add the error handling enums to the module.\n if (PyModule_AddIntConstant(m, \"ERROR_CALL\", to_underlying(tok::OnError::CALL)) != 0)\n return nullptr;\n if (PyModule_AddIntConstant(m, \"ERROR_SKIP\", to_underlying(tok::OnError::SKIP)) != 0)\n return nullptr;\n if (PyModule_AddIntConstant(m, \"ERROR_THROW\", to_underlying(tok::OnError::THROW)) != 0)\n return nullptr;\n\n return m;\n}\n\n\nPyMODINIT_FUNC\n#ifdef IS_PY3K\ninittokenizer(void) {\n#else\nPyInit_tokenizer(void) {\n#endif\n PyObject *const m = _inittokenizer();\n if (m == nullptr && PyErr_Occurred()) {\n PyErr_SetString(PyExc_ImportError, \"tokenizer: init failed\");\n SCHWA_PY_MODULE_INIT_RETURN_ERROR(m);\n }\n\n SCHWA_PY_MODULE_INIT_RETURN_SUCCESS(m);\n}\nCorrected swapped module initialisation function names.\/* -*- Mode: C++; indent-tabs-mode: nil -*- *\/\n#include \"_python.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"callback_stream.h\"\n#include \"exception.h\"\n#include \"pystream.h\"\n#include \"seq_stream.h\"\n#include \"text_stream.h\"\n\nnamespace io = schwa::io;\nnamespace tok = schwa::tokenizer;\n\nusing schwa::to_underlying;\n\n\n\/\/ ============================================================================\n\/\/ Module-level objects\n\/\/ ============================================================================\nstatic PyObject *module_TokenError = nullptr;\n\n\n\/\/ ============================================================================\n\/\/ PyTokenizer\n\/\/ ============================================================================\ntypedef struct {\n PyObject_HEAD\n tok::Tokenizer *tokenizer;\n} PyTokenizer;\n\n\nstatic PyObject *\nPyTokenizer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {\n PyTokenizer *self = (PyTokenizer *)type->tp_alloc(type, 0);\n if (self != nullptr)\n self->tokenizer = new tok::Tokenizer();\n return (PyObject *)self;\n}\n\n\nstatic void\nPyTokenizer_dealloc(PyTokenizer *self) {\n PyObject *const pyself = (PyObject *)self;\n delete self->tokenizer;\n pyself->ob_type->tp_free(pyself);\n}\n\n\nstatic const char *const PyTokenizer_tokenize__doc =\n \"Identifies paragraph, sentence and token boundaries in (English) text or HTML,\\n\"\n \"using a rule-based lexer.\\n\"\n \"\\n\"\n \"Arguments:\\n\"\n \"\\n\"\n \" source: a UTF-8 byte string\\n\"\n \"\\n\"\n \" dest: the output method, one of the following Python types:\\n\"\n \" - str (default): outputs a UTF-8 string with '\\\\n\\\\n', '\\\\n' and ' ' as\\n\"\n \" paragraph, sentence and token delimiters respectively\\n\"\n \" - unicode: like str, but with UTF-8 decoded\\n\"\n \" - list: outputs a list of paragraphs, each containing a list of sentences,\\n\"\n \" each containing a list of (offset, raw_token, [normalised_token]) tuples\\n\"\n \" or:\\n\"\n \" - any other callable: makes callbacks with arguments\\n\"\n \" (emit_type, offset, raw, norm)\\n\"\n \" - any other object: calls methods named according to emit_type when present\\n\"\n \"\\n\"\n \" Offset is a byte offset into the input string.\\n\"\n \" Emit types are:\\n\"\n \" begin_{document,paragraph,sentence,heading,list,item},\\n\"\n \" end_{document,paragraph,sentence,heading,list,item},\\n\"\n \" token and error\\n\"\n \"\\n\"\n \" filename: the path to a file to use instead of source\\n\"\n \"\\n\"\n \" buffer_size: \\n\"\n \"\\n\"\n \" errors: a method for dealing with bad byte sequences, may be one of:\\n\"\n \" - ERROR_SKIP (default): ignores errors\\n\"\n \" - ERROR_CALL: emits ('error', offset, bytes)\\n\"\n \" - ERROR_THROW: throws a TokenError\\n\"\n \"\\n\"\n \" normalise: a boolean (default True) indicating whether to perform\\n\"\n \" normalisation on the output (such as directed quotes, all dashes as --, and\\n\"\n \" * to indicate list items). Only applies when dest is str or unicode.\\n\"\n \"\\n\"\n \" mmap: a boolean (default False) indicating whether to process the file\\n\"\n \" memory-mapped, when the filename argument is used.\";\n\nPyObject *\nPyTokenizer_tokenize(PyTokenizer *self, PyObject *args, PyObject *kwargs) {\n \/\/ Setup default values for kwarg parsing.\n PyObject *pysrc = nullptr;\n PyObject *pydest = (PyObject *)&SCHWA_PY_BYTES_TYPE;\n const char *filename = nullptr;\n Py_ssize_t buffer_size = static_cast(tok::DEFAULT_BUFFER_SIZE);\n int pyerrors = to_underlying(tok::OnError::SKIP);\n int normalise = 1;\n int use_mmap = 0;\n\n \/\/ Parse the kwargs.\n static const char *kwlist[] = {\"source\", \"dest\", \"filename\", \"buffer_size\", \"errors\", \"normalise\", \"mmap\", 0};\n if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OOsniii:tokenize\", (char **)kwlist, &pysrc, &pydest, &filename, &buffer_size, &pyerrors, &normalise, &use_mmap))\n return 0;\n\n \/\/ Validate the arguments.\n if (!pysrc && !filename)\n return PyErr_Format(PyExc_TypeError, \"tokenize() requires either a source or filename argument\");\n if (pysrc) {\n if (PyUnicode_Check(pysrc))\n return PyErr_Format(PyExc_TypeError, \"tokenize() does not accept unicode objects, use unicode.encode('utf-8')\");\n else if (!SCHWA_PY_CHECK_BUFFER(pysrc))\n return PyErr_Format(PyExc_TypeError, \"tokenize() source must support the buffer interface\");\n }\n if (buffer_size <= 0)\n return PyErr_Format(PyExc_ValueError, \"tokenize() buffer_size must be positive, %zu given\", buffer_size);\n tok::OnError onerror = tok::OnError::SKIP;\n switch (pyerrors) {\n case to_underlying(tok::OnError::CALL):\n onerror = tok::OnError::CALL;\n break;\n case to_underlying(tok::OnError::SKIP):\n onerror = tok::OnError::SKIP;\n break;\n case to_underlying(tok::OnError::THROW):\n onerror = tok::OnError::THROW;\n break;\n default:\n return PyErr_Format(PyExc_ValueError, \"tokenize() unknown bad byte error handler, %d given\", pyerrors);\n }\n\n try {\n \/\/ Work out what the destination for the tokenizers output should be.\n std::unique_ptr stream;\n if ((void *)pydest == (void *)&SCHWA_PY_BYTES_TYPE)\n stream.reset(new tok::PyBytesStream(normalise));\n else if ((void *)pydest == (void *)&PyUnicode_Type)\n stream.reset(new tok::PyUnicodeStream(normalise));\n else if ((void *)pydest == (void *)&PyList_Type)\n stream.reset(new tok::PyListStream());\n else if ((void *)pydest == (void *)&PyTuple_Type)\n stream.reset(new tok::PyTupleStream());\n else if (PyCallable_Check(pydest))\n stream.reset(new tok::PyCallFuncStream(pydest));\n else\n stream.reset(new tok::PyCallObjectStream(pydest));\n\n \/\/ Call the appropriate tokenize method on the Tokenizer object.\n if (filename) {\n if (use_mmap)\n self->tokenizer->tokenize_mmap(*stream, filename, onerror);\n else {\n std::ifstream in(filename);\n if (!in)\n return PyErr_Format(PyExc_IOError, \"tokenize() could not open file '%s' for reading\", filename);\n self->tokenizer->tokenize_stream(*stream, in, static_cast(buffer_size), onerror);\n }\n }\n else {\n \/\/ Obtain the underlying buffer and pass it to the tokenizer, ensuring we release it.\n Py_buffer buffer;\n if (PyObject_GetBuffer(pysrc, &buffer, PyBUF_SIMPLE) != 0)\n return PyErr_Format(PyExc_ValueError, \"tokenize() only supports simple buffer objects\");\n if (buffer.len < 0)\n return PyErr_Format(PyExc_ValueError, \"Size of the provided source's underlying buffer is negative\");\n try {\n self->tokenizer->tokenize(*stream, (char *)buffer.buf, static_cast(buffer.len), onerror);\n }\n catch (...) {\n PyBuffer_Release(&buffer);\n throw;\n }\n }\n\n \/\/ Return what the stream defines is the return value for this function.\n return stream->return_value();\n }\n catch (tok::TokenError &e) {\n PyErr_SetString(module_TokenError, e.what());\n return nullptr;\n }\n catch (tok::PyRaise &e) {\n return nullptr;\n }\n catch (schwa::IOException &e) {\n PyErr_SetString(PyExc_IOError, e.what());\n return nullptr;\n }\n}\n\n\nstatic PyMethodDef PyTokenizer_methods[] = {\n {\"tokenize\", (PyCFunction)PyTokenizer_tokenize, METH_VARARGS | METH_KEYWORDS, PyTokenizer_tokenize__doc},\n {nullptr} \/* Sentinel *\/\n};\n\n\nstatic PyTypeObject PyTokenizerType = {\n PyVarObject_HEAD_INIT(nullptr, 0)\n \"tokenizer.Tokenizer\", \/* tp_name *\/\n sizeof(PyTokenizer), \/* tp_basicsize *\/\n 0, \/* tp_itemsize *\/\n (destructor)PyTokenizer_dealloc, \/* tp_dealloc *\/\n 0, \/* tp_print *\/\n 0, \/* tp_getattr *\/\n 0, \/* tp_setattr *\/\n 0, \/* tp_compare *\/\n 0, \/* tp_repr *\/\n 0, \/* tp_as_number *\/\n 0, \/* tp_as_sequence *\/\n 0, \/* tp_as_mapping *\/\n 0, \/* tp_hash *\/\n 0, \/* tp_call *\/\n 0, \/* tp_str *\/\n 0, \/* tp_getattro *\/\n 0, \/* tp_setattro *\/\n 0, \/* tp_as_buffer *\/\n Py_TPFLAGS_DEFAULT, \/* tp_flags *\/\n \"Wrapper around the C++ Tokenizer class.\", \/* tp_doc *\/\n 0, \/* tp_traverse *\/\n 0, \/* tp_clear *\/\n 0, \/* tp_richcompare *\/\n 0, \/* tp_weaklistoffset *\/\n 0, \/* tp_iter *\/\n 0, \/* tp_iternext *\/\n PyTokenizer_methods, \/* tp_methods *\/\n 0, \/* tp_members *\/\n 0, \/* tp_getset *\/\n 0, \/* tp_base *\/\n 0, \/* tp_dict *\/\n 0, \/* tp_descr_get *\/\n 0, \/* tp_descr_set *\/\n 0, \/* tp_dictoffset *\/\n (initproc)0, \/* tp_init *\/\n 0, \/* tp_alloc *\/\n PyTokenizer_new, \/* tp_new *\/\n};\n\n\n\/\/ ============================================================================\n\/\/ Module\n\/\/ ============================================================================\nstatic const char *const module_name = \"tokenizer\";\nstatic const char *const module_doc = \"Schwa Lab tokenizer module\";\n\nstatic PyMethodDef module_methods[] = {\n {nullptr} \/* Sentinel *\/\n};\n\n#ifdef IS_PY3K\nstatic PyModuleDef module_def = {\n PyModuleDef_HEAD_INIT, \/* m_base *\/\n module_name, \/* m_name *\/\n module_doc, \/* m_doc *\/\n 0, \/* m_size *\/\n module_methods, \/* m_methods *\/\n nullptr, \/* m_reload *\/\n nullptr, \/* m_traverse *\/\n nullptr, \/* m_clear *\/\n nullptr, \/* m_free *\/\n};\n#endif\n\n\nstatic PyObject *\n_inittokenizer(void) {\n \/\/ Ensure that PyTokenizerType is ready for use.\n if (PyType_Ready(&PyTokenizerType) != 0)\n return nullptr;\n\n \/\/ Construct the module.\n#ifdef IS_PY3K\n PyObject *const m = PyModule_Create(&module_def);\n#else\n PyObject *const m = Py_InitModule3(module_name, module_methods, module_doc);\n#endif\n if (m == nullptr)\n return nullptr;\n\n \/\/ Add PyTokenizerType to the module.\n Py_INCREF(&PyTokenizerType);\n if (PyModule_AddObject(m, \"Tokenizer\", (PyObject *)&PyTokenizerType) != 0)\n return nullptr;\n\n \/\/ Create the TokenError exception and add it to the module.\n module_TokenError = PyErr_NewException((char *)\"tokenizer.TokenError\", nullptr, nullptr);\n if (module_TokenError == nullptr)\n return nullptr;\n Py_INCREF(&module_TokenError);\n if (PyModule_AddObject(m, \"TokenError\", module_TokenError) != 0)\n return nullptr;\n\n \/\/ Add the error handling enums to the module.\n if (PyModule_AddIntConstant(m, \"ERROR_CALL\", to_underlying(tok::OnError::CALL)) != 0)\n return nullptr;\n if (PyModule_AddIntConstant(m, \"ERROR_SKIP\", to_underlying(tok::OnError::SKIP)) != 0)\n return nullptr;\n if (PyModule_AddIntConstant(m, \"ERROR_THROW\", to_underlying(tok::OnError::THROW)) != 0)\n return nullptr;\n\n return m;\n}\n\n\nPyMODINIT_FUNC\n#ifdef IS_PY3K\nPyInit_tokenizer(void) {\n#else\ninittokenizer(void) {\n#endif\n PyObject *const m = _inittokenizer();\n if (m == nullptr && PyErr_Occurred()) {\n PyErr_SetString(PyExc_ImportError, \"tokenizer: init failed\");\n SCHWA_PY_MODULE_INIT_RETURN_ERROR(m);\n }\n\n SCHWA_PY_MODULE_INIT_RETURN_SUCCESS(m);\n}\n<|endoftext|>"} {"text":"\/* Copyright 2016 Stanford University, NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain 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 \"legion_terra_partitions.h\"\n#include \"legion_terra_partitions_cxx.h\"\n\n#include \"arrays.h\"\n#include \"legion.h\"\n#include \"legion_c_util.h\"\n#include \"legion_utilities.h\"\n#include \"lowlevel.h\"\n#include \"utilities.h\"\n\n#ifdef SHARED_LOWLEVEL\n#define USE_LEGION_CROSS_PRODUCT 1\n#else\n\/\/ General LLR can't handle new partion API yet.\n#define USE_LEGION_CROSS_PRODUCT 0\n#endif\n\n#ifndef USE_TLS\n\/\/ Mac OS X and GCC <= 4.7 do not support C++11 thread_local.\n#if __cplusplus < 201103L || defined(__MACH__) || (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ <= 7)))\n#define USE_TLS 0\n#else\n#define USE_TLS 1\n#endif\n#endif\n\nstruct CachedIndexIterator {\npublic:\n CachedIndexIterator(HighLevelRuntime *rt, Context ctx, IndexSpace is, bool gl)\n : runtime(rt), context(ctx), space(is), index(0), cached(false), global(gl)\n {\n }\n\n bool has_next() {\n if (!cached) cache();\n return index < spans.size();\n }\n\n ptr_t next_span(size_t *count) {\n if (!cached) cache();\n if (index >= spans.size()) {\n *count = 0;\n return ptr_t::nil();\n }\n std::pair span = spans[index++];\n *count = span.second;\n return span.first;\n }\n\n void reset() {\n index = 0;\n }\n\nprivate:\n void cache() {\n assert(!cached);\n\n if (global) {\n#if !USE_TLS\n LegionRuntime::HighLevel::AutoLock guard(global_lock);\n#endif\n std::map > >::iterator it =\n global_cache.find(space);\n if (it != global_cache.end()) {\n spans = it->second;\n cached = true;\n return;\n }\n }\n\n IndexIterator it(runtime, context, space);\n while (it.has_next()) {\n size_t count = 0;\n ptr_t start = it.next_span(count);\n assert(count && !start.is_null());\n spans.push_back(std::pair(start, count));\n }\n\n if (global) {\n#if USE_TLS\n global_cache[space] = spans;\n#else\n LegionRuntime::HighLevel::AutoLock guard(global_lock);\n if (!global_cache.count(space)) {\n global_cache[space] = spans;\n }\n#endif\n }\n\n cached = true;\n }\n\nprivate:\n HighLevelRuntime *runtime;\n Context context;\n IndexSpace space;\n std::vector > spans;\n size_t index;\n bool cached;\n bool global;\nprivate:\n#if USE_TLS\n static thread_local\n std::map > > global_cache;\n#else\n static std::map > > global_cache;\n static ImmovableLock global_lock;\n#endif\n};\n\n#if USE_TLS\nthread_local std::map > >\n CachedIndexIterator::global_cache;\n#else\nstd::map > >\n CachedIndexIterator::global_cache;\nImmovableLock CachedIndexIterator::global_lock(true);\n#endif\n\nclass TerraCObjectWrapper {\npublic:\n\n#define NEW_OPAQUE_WRAPPER(T_, T) \\\n static T_ wrap(T t) { \\\n T_ t_; \\\n t_.impl = static_cast(t); \\\n return t_; \\\n } \\\n static const T_ wrap_const(const T t) { \\\n T_ t_; \\\n t_.impl = const_cast(static_cast(t)); \\\n return t_; \\\n } \\\n static T unwrap(T_ t_) { \\\n return static_cast(t_.impl); \\\n } \\\n static const T unwrap_const(const T_ t_) { \\\n return static_cast(t_.impl); \\\n }\n\n NEW_OPAQUE_WRAPPER(legion_terra_cached_index_iterator_t, CachedIndexIterator *);\n#undef NEW_OPAQUE_WRAPPER\n};\n\nvoid\ncreate_cross_product(HighLevelRuntime *runtime,\n Context ctx,\n IndexPartition lhs,\n IndexPartition rhs,\n Color rhs_color \/* = -1 *\/)\n{\n if (rhs_color == (Color)-1) {\n rhs_color = runtime->get_index_partition_color(ctx, rhs);\n }\n\n#if USE_LEGION_CROSS_PRODUCT\n std::map handles;\n runtime->create_cross_product_partitions(\n ctx, lhs, rhs, handles,\n (runtime->is_index_partition_disjoint(ctx, rhs) ? DISJOINT_KIND : ALIASED_KIND),\n rhs_color, true);\n#else\n \/\/ FIXME: Validate: same index tree\n\n Domain lhs_colors = runtime->get_index_partition_color_space(ctx, lhs);\n Domain rhs_colors = runtime->get_index_partition_color_space(ctx, rhs);\n\n for (Domain::DomainPointIterator lh_dp(lhs_colors); lh_dp; lh_dp++) {\n Color lh_color = lh_dp.p.get_point<1>()[0];\n IndexSpace lh_space = runtime->get_index_subspace(ctx, lhs, lh_color);\n\n Coloring lh_coloring;\n for (Domain::DomainPointIterator rh_dp(rhs_colors); rh_dp; rh_dp++) {\n Color rh_color = rh_dp.p.get_point<1>()[0];\n IndexSpace rh_space = runtime->get_index_subspace(ctx, rhs, rh_color);\n\n \/\/ Ensure the color exists.\n lh_coloring[rh_color];\n\n for (IndexIterator lh_it(runtime, ctx, lh_space); lh_it.has_next();) {\n size_t lh_count = 0;\n ptr_t lh_ptr = lh_it.next_span(lh_count);\n ptr_t lh_end = lh_ptr.value + lh_count - 1;\n\n for (IndexIterator rh_it(runtime, ctx, rh_space, lh_ptr); rh_it.has_next();) {\n size_t rh_count = 0;\n ptr_t rh_ptr = rh_it.next_span(rh_count);\n ptr_t rh_end = rh_ptr.value + rh_count - 1;\n if (rh_ptr.value > lh_end.value) {\n break;\n }\n\n if (rh_end.value > lh_end.value) {\n lh_coloring[rh_color].ranges.insert(std::pair(rh_ptr, lh_end));\n break;\n }\n\n lh_coloring[rh_color].ranges.insert(std::pair(rh_ptr, rh_end));\n }\n }\n }\n\n runtime->create_index_partition(\n ctx, lh_space, lh_coloring,\n runtime->is_index_partition_disjoint(ctx, rhs),\n rhs_color);\n }\n#endif\n}\nstatic void\ncreate_cross_product_multi(HighLevelRuntime *runtime,\n Context ctx,\n size_t npartitions,\n IndexPartition next,\n std::vector::iterator rest,\n std::vector::iterator end,\n int level)\n{\n if (rest != end) {\n create_cross_product(runtime, ctx, next, *rest);\n Domain colors = runtime->get_index_partition_color_space(ctx, next);\n Color color2 = runtime->get_index_partition_color(ctx, *rest);\n for (Domain::DomainPointIterator dp(colors); dp; dp++) {\n Color color = dp.p.get_point<1>()[0];\n IndexSpace is = runtime->get_index_subspace(ctx, next, color);\n IndexPartition ip = runtime->get_index_partition(ctx, is, color2);\n create_cross_product_multi(runtime, ctx, npartitions - 1, ip, rest+1, end, level + 1);\n }\n }\n}\n\nlegion_terra_index_cross_product_t\nlegion_terra_index_cross_product_create(legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_partition_t lhs_,\n legion_index_partition_t rhs_)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexPartition lhs = CObjectWrapper::unwrap(lhs_);\n IndexPartition rhs = CObjectWrapper::unwrap(rhs_);\n\n create_cross_product(runtime, ctx, lhs, rhs);\n\n legion_terra_index_cross_product_t result;\n result.partition = CObjectWrapper::wrap(lhs);\n result.other = CObjectWrapper::wrap(rhs);\n return result;\n}\n\nlegion_terra_index_cross_product_t\nlegion_terra_index_cross_product_create_multi(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_partition_t *partitions_,\n size_t npartitions)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n\n std::vector partitions;\n for (size_t i = 0; i < npartitions; i++) {\n partitions.push_back(CObjectWrapper::unwrap(partitions_[i]));\n }\n\n assert(npartitions >= 2);\n create_cross_product_multi(runtime, ctx, npartitions,\n partitions[0],\n partitions.begin() + 1, partitions.end(), 0);\n\n legion_terra_index_cross_product_t result;\n result.partition = CObjectWrapper::wrap(partitions[0]);\n result.other = CObjectWrapper::wrap(partitions[1]);\n return result;\n}\n\nlegion_index_partition_t\nlegion_terra_index_cross_product_get_partition(\n legion_terra_index_cross_product_t prod)\n{\n return prod.partition;\n}\n\nlegion_index_partition_t\nlegion_terra_index_cross_product_get_subpartition_by_color(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_terra_index_cross_product_t prod,\n legion_color_t color)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexPartition partition = CObjectWrapper::unwrap(prod.partition);\n IndexPartition other = CObjectWrapper::unwrap(prod.other);\n\n IndexSpace is = runtime->get_index_subspace(ctx, partition, color);\n IndexPartition ip = runtime->get_index_partition(\n ctx, is, runtime->get_index_partition_color(ctx, other));\n return CObjectWrapper::wrap(ip);\n}\n\nlegion_terra_cached_index_iterator_t\nlegion_terra_cached_index_iterator_create(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_space_t handle_)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexSpace handle = CObjectWrapper::unwrap(handle_);\n\n CachedIndexIterator *result = new CachedIndexIterator(runtime, ctx, handle, true);\n return TerraCObjectWrapper::wrap(result);\n}\n\nvoid\nlegion_terra_cached_index_iterator_destroy(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n delete handle;\n}\n\nbool\nlegion_terra_cached_index_iterator_has_next(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n return handle->has_next();\n}\n\nlegion_ptr_t\nlegion_terra_cached_index_iterator_next_span(\n legion_terra_cached_index_iterator_t handle_,\n size_t *count,\n size_t req_count \/* must be -1 *\/)\n{\n assert(req_count == size_t(-1));\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n ptr_t result = handle->next_span(count);\n return CObjectWrapper::wrap(result);\n}\n\nvoid\nlegion_terra_cached_index_iterator_reset(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n handle->reset();\n}\n\nunsigned\nlegion_terra_task_launcher_get_region_requirement_logical_region(\n legion_task_launcher_t launcher_,\n legion_logical_region_t region_)\n{\n TaskLauncher *launcher = CObjectWrapper::unwrap(launcher_);\n LogicalRegion region = CObjectWrapper::unwrap(region_);\n\n unsigned idx = (unsigned)-1;\n for (unsigned i = 0; i < launcher->region_requirements.size(); i++) {\n if (launcher->region_requirements[i].handle_type == SINGULAR &&\n launcher->region_requirements[i].region == region) {\n idx = i;\n break;\n }\n }\n return idx;\n}\n\nbool\nlegion_terra_task_launcher_has_field(\n legion_task_launcher_t launcher_,\n unsigned idx,\n legion_field_id_t fid)\n{\n TaskLauncher *launcher = CObjectWrapper::unwrap(launcher_);\n const RegionRequirement &req = launcher->region_requirements[idx];\n return req.privilege_fields.count(fid) > 0;\n}\nbindings: Some heuristics to determine which way to run the cross-product.\/* Copyright 2016 Stanford University, NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain 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 \"legion_terra_partitions.h\"\n#include \"legion_terra_partitions_cxx.h\"\n\n#include \"arrays.h\"\n#include \"legion.h\"\n#include \"legion_c_util.h\"\n#include \"legion_utilities.h\"\n#include \"lowlevel.h\"\n#include \"utilities.h\"\n\n#ifdef SHARED_LOWLEVEL\n#define USE_LEGION_CROSS_PRODUCT 1\n#else\n\/\/ General LLR can't handle new partion API yet.\n#define USE_LEGION_CROSS_PRODUCT 0\n#endif\n\n#ifndef USE_TLS\n\/\/ Mac OS X and GCC <= 4.7 do not support C++11 thread_local.\n#if __cplusplus < 201103L || defined(__MACH__) || (defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ <= 7)))\n#define USE_TLS 0\n#else\n#define USE_TLS 1\n#endif\n#endif\n\nstruct CachedIndexIterator {\npublic:\n CachedIndexIterator(HighLevelRuntime *rt, Context ctx, IndexSpace is, bool gl)\n : runtime(rt), context(ctx), space(is), index(0), cached(false), global(gl)\n {\n }\n\n bool has_next() {\n if (!cached) cache();\n return index < spans.size();\n }\n\n ptr_t next_span(size_t *count) {\n if (!cached) cache();\n if (index >= spans.size()) {\n *count = 0;\n return ptr_t::nil();\n }\n std::pair span = spans[index++];\n *count = span.second;\n return span.first;\n }\n\n void reset() {\n index = 0;\n }\n\nprivate:\n void cache() {\n assert(!cached);\n\n if (global) {\n#if !USE_TLS\n LegionRuntime::HighLevel::AutoLock guard(global_lock);\n#endif\n std::map > >::iterator it =\n global_cache.find(space);\n if (it != global_cache.end()) {\n spans = it->second;\n cached = true;\n return;\n }\n }\n\n IndexIterator it(runtime, context, space);\n while (it.has_next()) {\n size_t count = 0;\n ptr_t start = it.next_span(count);\n assert(count && !start.is_null());\n spans.push_back(std::pair(start, count));\n }\n\n if (global) {\n#if USE_TLS\n global_cache[space] = spans;\n#else\n LegionRuntime::HighLevel::AutoLock guard(global_lock);\n if (!global_cache.count(space)) {\n global_cache[space] = spans;\n }\n#endif\n }\n\n cached = true;\n }\n\nprivate:\n HighLevelRuntime *runtime;\n Context context;\n IndexSpace space;\n std::vector > spans;\n size_t index;\n bool cached;\n bool global;\nprivate:\n#if USE_TLS\n static thread_local\n std::map > > global_cache;\n#else\n static std::map > > global_cache;\n static ImmovableLock global_lock;\n#endif\n};\n\n#if USE_TLS\nthread_local std::map > >\n CachedIndexIterator::global_cache;\n#else\nstd::map > >\n CachedIndexIterator::global_cache;\nImmovableLock CachedIndexIterator::global_lock(true);\n#endif\n\nclass TerraCObjectWrapper {\npublic:\n\n#define NEW_OPAQUE_WRAPPER(T_, T) \\\n static T_ wrap(T t) { \\\n T_ t_; \\\n t_.impl = static_cast(t); \\\n return t_; \\\n } \\\n static const T_ wrap_const(const T t) { \\\n T_ t_; \\\n t_.impl = const_cast(static_cast(t)); \\\n return t_; \\\n } \\\n static T unwrap(T_ t_) { \\\n return static_cast(t_.impl); \\\n } \\\n static const T unwrap_const(const T_ t_) { \\\n return static_cast(t_.impl); \\\n }\n\n NEW_OPAQUE_WRAPPER(legion_terra_cached_index_iterator_t, CachedIndexIterator *);\n#undef NEW_OPAQUE_WRAPPER\n};\n\n#if !USE_LEGION_CROSS_PRODUCT\nstatic void\ncreate_cross_product_coloring(HighLevelRuntime *runtime,\n Context ctx,\n IndexPartition lhs,\n IndexPartition rhs,\n std::map &coloring)\n{\n Domain lhs_colors = runtime->get_index_partition_color_space(ctx, lhs);\n Domain rhs_colors = runtime->get_index_partition_color_space(ctx, rhs);\n\n for (Domain::DomainPointIterator lh_dp(lhs_colors); lh_dp; lh_dp++) {\n Color lh_color = lh_dp.p.get_point<1>()[0];\n IndexSpace lh_space = runtime->get_index_subspace(ctx, lhs, lh_color);\n\n for (Domain::DomainPointIterator rh_dp(rhs_colors); rh_dp; rh_dp++) {\n Color rh_color = rh_dp.p.get_point<1>()[0];\n IndexSpace rh_space = runtime->get_index_subspace(ctx, rhs, rh_color);\n\n for (IndexIterator lh_it(runtime, ctx, lh_space); lh_it.has_next();) {\n size_t lh_count = 0;\n ptr_t lh_ptr = lh_it.next_span(lh_count);\n ptr_t lh_end = lh_ptr.value + lh_count - 1;\n\n for (IndexIterator rh_it(runtime, ctx, rh_space, lh_ptr); rh_it.has_next();) {\n size_t rh_count = 0;\n ptr_t rh_ptr = rh_it.next_span(rh_count);\n ptr_t rh_end = rh_ptr.value + rh_count - 1;\n if (rh_ptr.value > lh_end.value) {\n break;\n }\n\n if (rh_end.value > lh_end.value) {\n coloring[lh_color][rh_color].ranges.insert(std::pair(rh_ptr, lh_end));\n break;\n }\n\n coloring[lh_color][rh_color].ranges.insert(std::pair(rh_ptr, rh_end));\n }\n }\n }\n }\n}\n#endif\n\nvoid\ncreate_cross_product(HighLevelRuntime *runtime,\n Context ctx,\n IndexPartition lhs,\n IndexPartition rhs,\n Color rhs_color \/* = -1 *\/)\n{\n if (rhs_color == (Color)-1) {\n rhs_color = runtime->get_index_partition_color(ctx, rhs);\n }\n\n#if USE_LEGION_CROSS_PRODUCT\n std::map handles;\n runtime->create_cross_product_partitions(\n ctx, lhs, rhs, handles,\n (runtime->is_index_partition_disjoint(ctx, rhs) ? DISJOINT_KIND : ALIASED_KIND),\n rhs_color, true);\n#else\n \/\/ FIXME: Validate: same index tree\n\n Domain lhs_colors = runtime->get_index_partition_color_space(ctx, lhs);\n Domain rhs_colors = runtime->get_index_partition_color_space(ctx, rhs);\n\n \/\/ The efficiency of this algorithm depends heavily on how many\n \/\/ spans are in lhs and rhs. Since it is *MUCH* better to have a\n \/\/ smaller number of spans on lhs, it is worth spending a little\n \/\/ time here estimating which will have fewer spans.\n\n bool flip = false;\n for (Domain::DomainPointIterator lh_dp(lhs_colors), rh_dp(rhs_colors); lh_dp && rh_dp;) {\n Color lh_color = lh_dp.p.get_point<1>()[0];\n IndexSpace lh_space = runtime->get_index_subspace(ctx, lhs, lh_color);\n Color rh_color = rh_dp.p.get_point<1>()[0];\n IndexSpace rh_space = runtime->get_index_subspace(ctx, rhs, rh_color);\n\n IndexIterator lh_it(runtime, ctx, lh_space);\n IndexIterator rh_it(runtime, ctx, rh_space);\n for (; lh_it.has_next() && rh_it.has_next();) {\n size_t lh_count = 0;\n lh_it.next_span(lh_count);\n size_t rh_count = 0;\n rh_it.next_span(rh_count);\n }\n\n flip = lh_it.has_next() && !rh_it.has_next();\n break;\n }\n\n std::map coloring;\n if (flip) {\n create_cross_product_coloring(runtime, ctx, rhs, lhs, coloring);\n } else {\n create_cross_product_coloring(runtime, ctx, lhs, rhs, coloring);\n }\n\n for (Domain::DomainPointIterator lh_dp(lhs_colors); lh_dp; lh_dp++) {\n Color lh_color = lh_dp.p.get_point<1>()[0];\n IndexSpace lh_space = runtime->get_index_subspace(ctx, lhs, lh_color);\n\n Coloring empty; \/\/ Make sure this stays on the stack while we need it...\n Coloring &lh_coloring = flip ? empty : coloring[lh_color];\n for (Domain::DomainPointIterator rh_dp(rhs_colors); rh_dp; rh_dp++) {\n Color rh_color = rh_dp.p.get_point<1>()[0];\n\n \/\/ Flip order of coloring.\n if (flip) {\n lh_coloring[rh_color] = coloring[rh_color][lh_color];\n }\n\n \/\/ Ensure the color exists.\n lh_coloring[rh_color];\n }\n\n runtime->create_index_partition(\n ctx, lh_space, lh_coloring,\n runtime->is_index_partition_disjoint(ctx, rhs),\n rhs_color);\n }\n#endif\n}\nstatic void\ncreate_cross_product_multi(HighLevelRuntime *runtime,\n Context ctx,\n size_t npartitions,\n IndexPartition next,\n std::vector::iterator rest,\n std::vector::iterator end,\n int level)\n{\n if (rest != end) {\n create_cross_product(runtime, ctx, next, *rest);\n Domain colors = runtime->get_index_partition_color_space(ctx, next);\n Color color2 = runtime->get_index_partition_color(ctx, *rest);\n for (Domain::DomainPointIterator dp(colors); dp; dp++) {\n Color color = dp.p.get_point<1>()[0];\n IndexSpace is = runtime->get_index_subspace(ctx, next, color);\n IndexPartition ip = runtime->get_index_partition(ctx, is, color2);\n create_cross_product_multi(runtime, ctx, npartitions - 1, ip, rest+1, end, level + 1);\n }\n }\n}\n\nlegion_terra_index_cross_product_t\nlegion_terra_index_cross_product_create(legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_partition_t lhs_,\n legion_index_partition_t rhs_)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexPartition lhs = CObjectWrapper::unwrap(lhs_);\n IndexPartition rhs = CObjectWrapper::unwrap(rhs_);\n\n create_cross_product(runtime, ctx, lhs, rhs);\n\n legion_terra_index_cross_product_t result;\n result.partition = CObjectWrapper::wrap(lhs);\n result.other = CObjectWrapper::wrap(rhs);\n return result;\n}\n\nlegion_terra_index_cross_product_t\nlegion_terra_index_cross_product_create_multi(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_partition_t *partitions_,\n size_t npartitions)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n\n std::vector partitions;\n for (size_t i = 0; i < npartitions; i++) {\n partitions.push_back(CObjectWrapper::unwrap(partitions_[i]));\n }\n\n assert(npartitions >= 2);\n create_cross_product_multi(runtime, ctx, npartitions,\n partitions[0],\n partitions.begin() + 1, partitions.end(), 0);\n\n legion_terra_index_cross_product_t result;\n result.partition = CObjectWrapper::wrap(partitions[0]);\n result.other = CObjectWrapper::wrap(partitions[1]);\n return result;\n}\n\nlegion_index_partition_t\nlegion_terra_index_cross_product_get_partition(\n legion_terra_index_cross_product_t prod)\n{\n return prod.partition;\n}\n\nlegion_index_partition_t\nlegion_terra_index_cross_product_get_subpartition_by_color(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_terra_index_cross_product_t prod,\n legion_color_t color)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexPartition partition = CObjectWrapper::unwrap(prod.partition);\n IndexPartition other = CObjectWrapper::unwrap(prod.other);\n\n IndexSpace is = runtime->get_index_subspace(ctx, partition, color);\n IndexPartition ip = runtime->get_index_partition(\n ctx, is, runtime->get_index_partition_color(ctx, other));\n return CObjectWrapper::wrap(ip);\n}\n\nlegion_terra_cached_index_iterator_t\nlegion_terra_cached_index_iterator_create(\n legion_runtime_t runtime_,\n legion_context_t ctx_,\n legion_index_space_t handle_)\n{\n HighLevelRuntime *runtime = CObjectWrapper::unwrap(runtime_);\n Context ctx = CObjectWrapper::unwrap(ctx_)->context();\n IndexSpace handle = CObjectWrapper::unwrap(handle_);\n\n CachedIndexIterator *result = new CachedIndexIterator(runtime, ctx, handle, true);\n return TerraCObjectWrapper::wrap(result);\n}\n\nvoid\nlegion_terra_cached_index_iterator_destroy(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n delete handle;\n}\n\nbool\nlegion_terra_cached_index_iterator_has_next(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n return handle->has_next();\n}\n\nlegion_ptr_t\nlegion_terra_cached_index_iterator_next_span(\n legion_terra_cached_index_iterator_t handle_,\n size_t *count,\n size_t req_count \/* must be -1 *\/)\n{\n assert(req_count == size_t(-1));\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n ptr_t result = handle->next_span(count);\n return CObjectWrapper::wrap(result);\n}\n\nvoid\nlegion_terra_cached_index_iterator_reset(\n legion_terra_cached_index_iterator_t handle_)\n{\n CachedIndexIterator *handle = TerraCObjectWrapper::unwrap(handle_);\n\n handle->reset();\n}\n\nunsigned\nlegion_terra_task_launcher_get_region_requirement_logical_region(\n legion_task_launcher_t launcher_,\n legion_logical_region_t region_)\n{\n TaskLauncher *launcher = CObjectWrapper::unwrap(launcher_);\n LogicalRegion region = CObjectWrapper::unwrap(region_);\n\n unsigned idx = (unsigned)-1;\n for (unsigned i = 0; i < launcher->region_requirements.size(); i++) {\n if (launcher->region_requirements[i].handle_type == SINGULAR &&\n launcher->region_requirements[i].region == region) {\n idx = i;\n break;\n }\n }\n return idx;\n}\n\nbool\nlegion_terra_task_launcher_has_field(\n legion_task_launcher_t launcher_,\n unsigned idx,\n legion_field_id_t fid)\n{\n TaskLauncher *launcher = CObjectWrapper::unwrap(launcher_);\n const RegionRequirement &req = launcher->region_requirements[idx];\n return req.privilege_fields.count(fid) > 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"v8.h\"\n#include \"libplatform\/libplatform.h\"\n#include \"binding.h\"\n\nusing namespace v8;\n\nstruct worker_s {\n int x;\n void* data;\n worker_recv_cb cb;\n Isolate* isolate;\n std::string last_exception;\n Persistent recv;\n Persistent context;\n};\n\n\/\/ Extracts a C string from a V8 Utf8Value.\nconst char* ToCString(const String::Utf8Value& value) {\n return *value ? *value : \"\";\n}\n\n\/\/ Exception details will be appended to the first argument.\nstd::string ExceptionString(Isolate* isolate, TryCatch* try_catch) {\n std::string out;\n size_t scratchSize = 100;\n char scratch[scratchSize]; \/\/ just some scratch space for sprintf\n\n HandleScope handle_scope(isolate);\n String::Utf8Value exception(try_catch->Exception());\n const char* exception_string = ToCString(exception);\n \n printf(\"exception string: %s\\n\", exception_string);\n\n Handle message = try_catch->Message();\n\n if (message.IsEmpty()) {\n \/\/ V8 didn't provide any extra information about this error; just\n \/\/ print the exception.\n out.append(exception_string);\n out.append(\"\\n\");\n } else {\n \/\/ Print (filename):(line number): (message).\n String::Utf8Value filename(message->GetScriptOrigin().ResourceName());\n const char* filename_string = ToCString(filename);\n int linenum = message->GetLineNumber();\n\n snprintf(scratch, scratchSize, \"%s:%i: %s\\n\", filename_string, linenum, exception_string);\n out.append(scratch);\n\n \/\/ Print line of source code.\n String::Utf8Value sourceline(message->GetSourceLine());\n const char* sourceline_string = ToCString(sourceline);\n\n out.append(sourceline_string);\n out.append(\"\\n\");\n\n \/\/ Print wavy underline (GetUnderline is deprecated).\n int start = message->GetStartColumn();\n for (int i = 0; i < start; i++) {\n out.append(\" \");\n }\n int end = message->GetEndColumn();\n for (int i = start; i < end; i++) {\n out.append(\"^\");\n }\n out.append(\"\\n\");\n String::Utf8Value stack_trace(try_catch->StackTrace());\n if (stack_trace.length() > 0) {\n const char* stack_trace_string = ToCString(stack_trace);\n out.append(stack_trace_string);\n out.append(\"\\n\");\n }\n }\n return out;\n}\n\n\nextern \"C\" {\n#include \"_cgo_export.h\"\n\nvoid go_recv_cb(const char* msg, void* data) {\n recvCb((char*)msg, data);\n}\n\n\nconst char* worker_version() {\n return V8::GetVersion();\n}\n\nconst char* worker_last_exception(worker* w) {\n return w->last_exception.c_str();\n}\n\nint worker_load(worker* w, char* name_s, char* source_s) {\n Locker locker(w->isolate);\n Isolate::Scope isolate_scope(w->isolate);\n HandleScope handle_scope(w->isolate);\n\n Local context = Local::New(w->isolate, w->context);\n Context::Scope context_scope(context);\n\n TryCatch try_catch;\n\n Local name = String::NewFromUtf8(w->isolate, name_s);\n Local source = String::NewFromUtf8(w->isolate, source_s);\n\n ScriptOrigin origin(name);\n\n Local